Asp.net core MVC post parameter always null

2019-01-14 02:56发布

I am new to MVC core.

I have created a project with MVC core which has a controller. This controller has Get and Post action methods. If i pass data to Get method using query string it works fine, but when i pass complex JSON to post method, then it always shows me null.

Here what i am doing:

Post Request

URL: http://localhost:1001/api/users
Content-Type: application/json
Body: 
{
   "Name":"UserName",
   "Gender":"Gender of the user",
   "PhoneNumber":"PhoneNumber of the user"
}

Here is the Post action method

[HttpPost]
[Route("api/users")]
public async Task<IActionResult> Post([FromBody]User newUser)
{
   ...
}

When post request is called, then newUser always shows me null. And if i remove [FromBody] attribute then i receive newUser object but all of its fields are null.

Please help me and guide me in this issue.

EDITED

Here is my User class

public class User{

   public int Id { get; set; }
   public string Name { get; set; }
   public string Gender { get; set; }
   public string PhoneNumber { get; set; }
}

I had done same as described here for json data, but still receives null.

5条回答
孤傲高冷的网名
2楼-- · 2019-01-14 03:08

Your User class must have a default parameterless constructor for this to work...

查看更多
啃猪蹄的小仙女
3楼-- · 2019-01-14 03:10

Are you on Microsoft.AspNetCore.Mvc 1.0.0?

If you are, try sending this object as your body in a request (camel cased properties):

{
   "name":"UserName",
   "gender":"Gender of the user",
   "phoneNumber":"PhoneNumber of the user"
}
查看更多
劫难
4楼-- · 2019-01-14 03:15

Note the original method Post([FromBody] User newUser)

For future readers from google, this same issue could arise if the method was Post(User newUser)

Note the lack of [FromBody]. This is a departure from previous versions of MVC where these parameters were generally inferred.

If you're an existing MVC5 developer who finds this page regarding AspNetCore.MVC, make sure to double check that you have [FromBody] decorated where relevant.

查看更多
Explosion°爆炸
5楼-- · 2019-01-14 03:22

This could be because of how the null values are being handled. Set NullValueHandling to Ignore in AddJsonOptions and see if that works.

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddMvc()
        .AddJsonOptions(jsonOptions=>
        {
            jsonOptions.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
        });
}
查看更多
放荡不羁爱自由
6楼-- · 2019-01-14 03:27

I created new ASP.NET Core project, added your functionality, and it works. Please, checkout this project on github.

Also, see screenshot of log with simple communication with this controller from browser console: Console output

查看更多
登录 后发表回答