.Net核心模型绑定JSON发布到Web API

.Net核心模型绑定JSON发布到Web API

问题描述:

只需使用.NET Core开始一个新项目.添加了我的Web API控制器和相关方法.使用Postman,我创建了一个JSON对象,并将其发布到我的控制器方法中.请记住,JSON对象与controller方法中的Object参数完全匹配.

Just started a new project using .NET Core. Added my Web API controller and related method. Using Postman I created a JSON object and posted it to my controller method. Bear in mind the JSON object matches the Object param in the controller method exactly.

在调试模式下,我可以看到该对象,它不是null,属性在那里,但是prop值默认为它们的代表类型,0表示int,等等.

In debug mode I can see the object, it is not null, the properties are there, HOWEVER the prop values are defaulted to their representatives types, 0 for int, etc.

我以前从未见过这种行为……所以我采用了完全相同的代码和对象,并使用Web API 2控制器将其复制到MVC项目中,并且效果很好.

I've never seen this behavior before… so I took exactly the same code and object and replicated in a MVC project with a Web API 2 controller and it works perfectly.

我缺少什么,我不能在.NET Core中发布JSON和模型绑定吗?

What am I missing, can I not POST JSON and model bind in .NET Core?

在阅读本文时,除非我以POST形式或以查询字符串vars的形式发送,否则我似乎无法这样做.

Reading this article it seems I cannot unless I send as form POST or as querystring vars which by the way works fine.

https://lbadri.wordpress.com/2014/11/23/web-api-model-binding-in-asp-net-mvc-6-asp-net-5/

JSON:

{
   "id": "4",
   "userId": "3"
   "dateOfTest": "7/13/2017"
}

方法:

[HttpPost]
[Route("test1")]
[AllowAnonymous]
public IActionResult Test(Class1 data)
{
    return Ok();
}

注意:如果您使用的是aspnet core 3.0,则可以找到该解决方案

NOTE: If you are using aspnet core 3.0, the solution can be found here. For other versions, keep reading.

您需要使用FromBody属性将您的参数标记为来自主体,如下所示:

You need to mark your parameter as coming from the body with the FromBody attribute like this:

[HttpPost]
[Route("test1")]
[AllowAnonymous]
public IActionResult Test([FromBody] Class1 data)
{
    return Ok();
}

您需要确保您使用的是application/json作为邮递员的内容类型:

You need to make sure you're using application/json as your content type from Postman:

结果:

确保您的财产设置者也公开:

Make sure your property setters are public as well:

public class Person
{
    public String Name;
    public Int32 Age;
}