在POST参数中接收空值

时间:2017-05-17 13:49:54

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

我总是在对控制器的web api rest post请求中收到一个空值

在我的控制器中

# ...
on_delete=models.DO_NOTHING,
# ...

模型

[HttpPost]
public HttpResponseMessage PostCustomer([FromBody]Customer customer)
{

       System.Diagnostics.Debug.WriteLine(customer); #CustomerApp.Models.Customer
       System.Diagnostics.Debug.WriteLine(customer.FirstName); #null

}

请求:

public class Customer
{
    public int Id { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }
}

我尝试了以下解决方案,但没有任何效果

https://myadventuresincoding.wordpress.com/2012/06/19/c-supporting-textplain-in-an-mvc-4-rc-web-api-application/

How to get POST data in WebAPI?

任何人都可以通过帮助或正确的链接指导我

答案: 提出了一个卷曲请求,而不是像邮差这样处理,这给了我解决方案

POST: http://localhost:21894/api/customer/postcustomer

Content-Type: application/json

body: {FirstName: "xxxx", LastName: 'yyyy'}

2 个答案:

答案 0 :(得分:5)

我认为您的意思是将Customer对象作为输入,而不是string

public HttpResponseMessage PostCustomer([FromBody]Customer customer)
 {

好了以下更改并尝试重新发布请求。它应该工作

public HttpResponseMessage PostCustomer(Customer customer)
 {
   return OK(customer.FirstName);
 }

请求:

POST: http://localhost:21894/api/customer/postcustomer
Content-Type: application/json; charset=utf-8
{"Id":101,"FirstName":"xxxx","LastName":'yyyy'}

答案 1 :(得分:3)

将您的实体设置为客户而非字符串

[HttpPost]
public Customer PostCustomer(Customer customer)
{
    System.Diagnostics.Debug.WriteLine(customer);
    return customer;
}

确保你的方法上有[HttpPost]属性也不需要[FromBody]