2015-10-16 79 views
1

我有一個非常簡單的WebAPI類,它返回JSON爲我的獲取方法。我郵政方法是:爲什麼我從Web API控制器上的Post方法獲取空值?

// POST: api/Diff 
    public void Post([FromBody]string value) 
    { 
     System.Diagnostics.Debug.WriteLine(value); 
    } 

和我打電話從控制檯應用程序兩種方法:

 using (var client = new HttpClient()) 
     { 
      // New code: 
      client.BaseAddress = new Uri("http://localhost:50541/"); 
      client.DefaultRequestHeaders.Accept.Clear(); 
      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

      // New code: 
      HttpResponseMessage response = await client.GetAsync("api/diff/1"); 
      if (response.IsSuccessStatusCode) 
      { 
       var diff = await response.Content.ReadAsAsync<Diff>(); 
       Console.WriteLine("{0}\t${1}", diff.Text, diff.Revision); 
      } 

      var blah = new Diff() { Text = "Gizmo", Revision = 999}; 
      response = await client.PostAsJsonAsync("api/diff", blah); 

獲取通話作品。我在調試器中驗證了在調用PostAsJson方法之前等於不爲空。但是,在API的post方法的調試器中,爲空。

回答

2

的方法期待一個string

public void Post([FromBody]string value) 

而你發送一個Diff

var blah = new Diff() { Text = "Gizmo", Revision = 999}; 
response = await client.PostAsJsonAsync("api/diff", blah); 

所以......

要麼改變它期待Diff

public void Post([FromBody]Diff value) 

發送一個字符串:

response = await client.PostAsJsonAsync("api/diff", new { value = "some string" }); 
2

您發送到控制器的複雜對象:

var blah = new Diff() { Text = "Gizmo", Revision = 999}; 

但你的控制器預計,請求體只有一個字符串名稱爲「價值」:

public void Post([FromBody]string value) 

一個可能的解決方案是將Post方法的參數更改爲Diff對象:

public void Post([FromBody]Diff diff) 
相關問題