从 Netcore 2.2 Web API 的响应中获取错误消息

Vir*_*tus 5 c# asp.net-core asp.net-core-2.2

我用空的用户名和密码调用 Register 方法。所以我收到了这个结果:

{
    "errors": {
        "Password": [
            "The Password field is required.",
            "Password length is between 4 and 8."
        ],
        "Username": [
            "The Username field is required."
        ]
    },
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "0HLJIO56EGJEV:00000001"
}
Run Code Online (Sandbox Code Playgroud)

我的 Dto:

public class UserForRegisterDto
{
    [Required]
    public string Username { get; set; }
    [Required]
    [StringLength(8, MinimumLength = 4, ErrorMessage = "Password length is between 4 and 8.")]
    public string Password { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我只想从响应中获取错误属性,我该怎么办?

Kir*_*kin 5

这是ASP.NET Core 2.2 中的一项新功能

一个IActionResult返回客户端错误状态代码(4XX)现在返回一个ProblemDetails体。

文档描述了打电话时,这可能是禁用AddMvc里面的ConfigureServices,就像这样:

services.AddMvc()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
    .ConfigureApiBehaviorOptions(options =>
    {
        options.SuppressUseValidationProblemDetailsForInvalidModelStateResponses = true;
    });
Run Code Online (Sandbox Code Playgroud)

这将导致 2.2 之前的行为,它只会序列化错误。