dotnet核心api模型绑定无效[frombody]

时间:2019-04-08 07:42:23

标签: asp.net .net api .net-core react-redux

我使用react-redux模板创建了一个简单的.netcore 2.1应用程序,其中有一个用于注册用户的API。控制器如下。

[HttpPost("register")]
public async Task<ActionResult<string>> Register(User user)
{
     await this._authService.Register(user);
     return Ok();
}

当我尝试使用控制器测试此API时,总是将用户的属性返回为null。以下是用户模型和邮递员请求。

public class User : IEntitybase
{
    [Key]
    public string Id { get; set; }
    [Required]
    public string Name {get; set;}
    [Required]
    public string Email {get; set;}
    [Required]
    public string Password {get; set;}

}

}

enter image description here

由于发送用户作为帖子正文不起作用,因此我尝试将用户参数作为查询参数发送,即使我没有提到从查询参数中获取参数,这也令人惊讶地起作用。

此后,我使用[FromBody]属性更改了API控制器,当我在正文中发送属性时,该属性仍然使用户为空。

默认情况下采用查询参数而不是取自正文可能是什么问题?

3 个答案:

答案 0 :(得分:0)

尝试使用诸如Postman之类的API客户端。

请求应为GET 请求标头应具有Content-Type作为“ application / json”,它可以是其他类型,但是请尝试将其启动。 将正文设置为

{
    "Id": "123",
    "Name": "some name",
    "Email": "someaddress@server.com",
    "Password": "somepwd"
}

答案 1 :(得分:0)

如果尚未在模型中使用[JsonProperty(PropertyName =“ FooBar”)],则属性名称应与POST数据匹配(区分大小写)。

在您的情况下,在邮递员中,

  1. 选择POST动词并输入有效的URL

  2. 在主体中选择原始-> JSON(应用程序/ json)

enter image description here

  1. 然后添加以下JSON正文-
{
    "Id" : "555",
    "Name" : "Some Name",
    "Email" : "EmailAddress@abc.com",
    "Password" : "Password"
}

答案 2 :(得分:0)

您丢失了:

当前

{
    "Id" : "555",
    "Name"   "Some Name",
    "Email" : "EmailAddress@abc.com",
    "Password"  "Password"
}

应该是什么

{
    "Id" : "555",
    "Name" : "Some Name",
    "Email" : "EmailAddress@abc.com",
    "Password" : "Password"
}
相关问题