c# - 在 POST 参数中接收空值

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

我总是在 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'}

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

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?

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

答案: 发出 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/

相关文章:

c# - 更新查询需要删除并重新插入所有相关项目,这会降低我的应用程序的速度

c# - 如何从 Windows 7 服务启动 session 1 中的进程

asp.net - 访问路径 'c:\inetpub\wwwroot\myapp\App_Data'被拒绝

c# - Enumerator.MoveNext() 在第一次调用时抛出 'Collection was Modified'

c# - 抛出什么样的异常?

c# - 如何在C#中获取IP地址?

c# - 这种制作相对路径的方法会起作用吗?

c# - 自定义控件错误

jquery - ASP TreeView 控件

c# - Iframe 从 C# 中的代码隐藏自动调整高度