Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

c# - .Net Core Model Binding JSON Post To Web API

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.

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.

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.

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

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"
}

Method:

[HttpPost]
[Route("test1")]
[AllowAnonymous]
public IActionResult Test(Class1 data)
{
    return Ok();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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();
}

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

Postman application/json

Resulting in:

json POST action

Make sure your property setters are public as well:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...