Asp.net core MVC post parameter always null

耗尽温柔 提交于 2019-11-27 20:37: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;
        });
}

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.

Roman Zinnatov

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

steamrolla

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!