简体   繁体   English

ASP.NET Core无法从主体获取对象

[英]ASP.NET Core can't get object from body

Code: 码:

[HttpPost("user/register")]
public IActionResult Register([FromBody] User user)
{
    if (user?.Name is null || user?.Password is null)
    {
        return BadRequest(new {message = "User is null and/or name and password are not provided"});
    }
    else
    {
         // Add to db
         return Json(user);
    }
}

Also the User class: 也是User类:

public class User
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Password { get; set; }
    public string Role { get; set; }
}


It should basically get a user and add it to the database. 它基本上应该获得一个用户并将其添加到数据库中。 I tried sending this json: 我尝试发送此json:

 { "Name": "Batman", "Password": "IronmanSucks"} 

The app caught the request, but the user object was null. 应用捕获了请求,但用户对象为null。 I also tried with: 我也尝试过:

 { "user": { "Name": "Batman", "Password": "IronmanSucks"} } 

But according to this documentation , the first json should have worked fine. 但是根据此文档 ,第一个json应该可以正常工作。

Here is a link to an example http request in postman 这是在邮递员中示例HTTP请求的链接


Does this have to do with the headers or is it a bug in .NET Core 2.0? 这是否与标题有关,还是.NET Core 2.0中的错误?

只有在类型没有无参数构造函数的情况下才会发生这种情况,因此可以通过添加此类简单地解决。

I believe that the Model is coming up as invalid hence why it is null. 我认为该模型无效,因此为什么它为空。 You should try adding a [BindNever] attribute into the User class for the Role and Guid properties, seeing as you aren't using them. 你应该尝试添加[BindNever]属性到User类的RoleGuid属性,如您不使用它们看到的。

If that doesn't work you may try using extended classes like so: 如果这样不起作用,您可以尝试使用扩展类,例如:

public class User
{
    public string Name { get; set; }
    public string Password { get; set; }
}

public class DataUser : User
{
    public Guid Id { get; set }
    public string Role { get; set; }
}

If you're using MVC Core instead of MVC , make sure you add Json Formaters (from Microsoft.AspNetCore.Mvc.Formatters.Json ). 如果您使用的是MVC Core而不是MVC ,请确保添加了Json Formaters (来自Microsoft.AspNetCore.Mvc.Formatters.Json )。 In your Startup.cs : 在您的Startup.cs中

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddMvcCore()
        .AddJsonFormatters();
}

This should help the [FromBody] to de-serialize your Post content 这应该有助于[FromBody]反序列化您的Post内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM