我总是在 web api rest 向 Controller 发送请求时收到一个空值
在我的 Controller 中
[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; }
}
要求:
POST: http://localhost:21894/api/customer/postcustomer
Content-Type: application/json
body: {FirstName: "xxxx", LastName: 'yyyy'}
我尝试了以下解决方案,但没有任何效果
How to get POST data in WebAPI?
任何人都可以通过帮助或正确的链接指导我
答案: 发出 curl 请求而不是像这样处理 postman 给了我解决方案
$ curl -H "Content-Type: application/json" -X POST -d '{"FirstName":"Jefferson","LastName":"sampaul"}' http://localhost
:21894/api/customer/postcustomer
最佳答案
我想你的意思是像下面这样输入一个 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'}
关于c# - 在 POST 参数中接收空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44026808/