2013-10-26 93 views
8

我試圖將C#對象傳遞給web api控制器。 api被配置爲存儲發佈給它的Product類型的對象。我已經使用Jquery Ajax方法成功添加了對象,現在我試圖在C#中獲得相同的結果。發送C#對象到webapi控制器

我創建了一個簡單的控制檯應用程序發送POST請求的API:

public class Product 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public string Category { get; set; } 
    public decimal Price { get; set; } 
} 

     static void Main(string[] args) 
    { 
     string apiUrl = @"http://localhost:3393/api/products"; 
     var client = new HttpClient(); 
     client.PostAsJsonAsync<Product>(apiUrl, new Product() { Id = 2, Name = "Jeans", Price = 200, Category = "Clothing" }); 

    } 

的postproduct方法永遠不會調用,如何將這些對象發送到控制器?用於添加物品

方法:

public HttpResponseMessage PostProduct([FromBody]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; 
    } 
+0

你的代碼看起來很好,你在小提琴手中看到了什麼?你在服務器上啓用了webapi跟蹤嗎? –

+0

我可以看到來自我使用的表單的請求,HttpClient發送的請求在提琴手中都不可見。 我也將api上傳到:http://producttestapi.azurewebsites.net/api/products,但沒有任何來自HttpClient的請求也達到了api要求。 – neo112

+0

此外,請檢查該網址的index.html,即我用於通過ajax發送對象的表單,該表單可以工作,因此API可以。 – neo112

回答

16

看起來你已經以某種方式禁用接受JSON作爲發佈格式。我能夠將數據發送到您的端點,並使用application/x-www-form-urlencoded創建新產品。這可能是你的jQuery請求如何做到的。

你能顯示你的web api的配置代碼嗎?你是否更改默認的格式化程序?

或者你可以從HttpClient發送一個表單。例如

string apiUrl = "http://producttestapi.azurewebsites.net/api/products"; 
    var client = new HttpClient(); 
    var values = new Dictionary<string, string>() 
     { 
      {"Id", "6"}, 
      {"Name", "Skis"}, 
      {"Price", "100"}, 
      {"Category", "Sports"} 
     }; 
    var content = new FormUrlEncodedContent(values); 

    var response = await client.PostAsync(apiUrl, content); 
    response.EnsureSuccessStatusCode(); 
+0

ajax方法有'dataType:'json''定義。所以這導致我認爲控制器仍然接受JSON作爲數據。我添加了處理將新對象添加到列表的方法。 我會顯示配置代碼,它是從App_Start文件夾中的.cs文件嗎? 與此同時,試試你在這裏發佈的approuch。 – neo112

+0

我能夠使用PostAsJson方法也使用您提供的代碼,現在它的工作原理。先生非常感謝您! – neo112

+0

如果我們在類中有像字符串數組這樣的參數,我們可以做什麼。由於FormUrlEncodedContent不接受Dictionary ,因此我無法將其設置爲Dictionary – Yasitha

相關問題