WebApi - 为什么我的帖子变量总是为空?

时间:2017-06-02 09:02:00

标签: c# asp.net-web-api2

我希望能够从我的控制器方法中读取一个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#中发送和接收post变量都是正确的,但是PartitionBuildDate变量始终为null。

1 个答案:

答案 0 :(得分: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;

此外,在您的Web API端,尝试将POST参数包装在类中:

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

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