2017-06-02 82 views
0

我希望能夠從我的控制器方法中讀取帖子變量。WebApi - 爲什麼我的post變量總是空?

目前,我有下面的代碼:

[HttpPost] 
public IHttpActionResult BuildPartitions([FromBody]string PartitionBuildDate) 
{ 
} 

我用下面的代碼進行測試:

using (HttpClient httpClient = new HttpClient()) 
{ 
    var values = new Dictionary<string, string> 
    { 
     { "PartitionBuildDate", "24-May-2017" } 
    }; 
    var content = new FormUrlEncodedContent(values); 
    var response = httpClient.PostAsync("http://localhost:55974/api/Controller/BuildPartitions", content); 
    var responseString = response.Result.Content; 
} 

網上看,這看起來是正確的發送和接收中的變量後C#,但是PartitionBuildDate變量始終爲空。

回答

1

嘗試添加content-type標題。我已經使用Newtonsoft JSON.NET對JSON轉換:

string postBody = JsonConvert.SerializeObject(yourDictionary); 

var response = client.PostAsync(url, new StringContent(postBody, Encoding.UTF8, "application/json")); 

var responseString = response.Result.Content; 

此外,在您的網頁API方面,儘量包裝類內部的POST參數:

public class PostParameters 
{ 
    public string PartitionBuildDate {get;set;} 
} 

[HttpPost] 
public IHttpActionResult BuildPartitions([FromBody]PostParameters parameters) 
{ 
    //you can access parameters.PartitionBuildDate 
}