2014-03-13 39 views
0

我正在使用WEB .API開發Web服務。我正在關注的example,其中包括:在Web API中創建POST方法

public HttpResponseMessage PostProduct(Product item) 
{ 
    item = repository.Add(item); 
    var response = Request.CreateResponse<Product>(HttpStatusCode.Created, item); 

    string uri = Url.Link("DefaultApi", new { id = item.Id }); 
    response.Headers.Location = new Uri(uri); 
    return response; 
} 

創建一個POST方法,允許客戶端發送的數據在崗ordert在數據庫中插入這些數據(我使用實體框架)。

然而,我想要做的事情略有不同,因爲我想傳遞給Web服務的數據不會與任何數據庫對象關聯:我有一些數據應該寫入多個表中。例如:

{"activity":"sport","customValue":"22","propertyIndex":"122-x"} 

的activty值(運動)應在一個表中所著,而其他兩個參數(customValueËproperyIndex)shouldBe這樣在另一個表所著。

所以我想我需要解析在POST中收到的json文件,然後執行兩個插入操作。

我該如何執行此任務?

回答

5

你需要創建結合活動網頁API項目的對象,CustomValue,PropertyIndex性能

public class MyTestClass 
    { 
     public string Activity { get; set; } 
     public string CustomValue { get; set; } 
     public string PropertyIndex { get; set; } 
    } 

和HttpPost將

[HttpPost] 
     public HttpResponseMessage Post(MyTestClass class) 
     { 
      // Save Code will be here 
      return new HttpResponseMessage(HttpStatusCode.OK); 
     } 
1

產品類應該有活動,CustomValue和PropertyIndex屬性與發佈的數據綁定。

[HttpPost] 
[ActionName("alias_for_action")] 
public HttpResponseMessage PostProduct([FromBody] Product item) 
{ 

    //your code here 

    var response = new HttpResponseMessage(HttpStatusCode.Created) 
    { 
     Content = new StringContent("Your Result") 
    }; 

    return response; 
} 

是,如果你想更新使用實體框架,那麼你必須執行兩個插入操作數據庫中的兩個表。