Get ErrorMessage from Response in Netcore 2.2 Web API

十年热恋 提交于 2019-12-22 11:35:48

问题


I call Register method with empty username and password. So I received this result:

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

My 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; }
}

I only want to get errors attribute from response, What should I do?


回答1:


This is a new feature in ASP.NET Core 2.2:

An IActionResult returning a client error status code (4xx) now returns a ProblemDetails body.

The docs describe that this can be disabled when calling AddMvc inside of ConfigureServices, like this:

services.AddMvc()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
    .ConfigureApiBehaviorOptions(options =>
    {
        options.SuppressUseValidationProblemDetailsForInvalidModelStateResponses = true;
    });

This will result in the pre-2.2 behavior, which will serialise only the errors.



来源:https://stackoverflow.com/questions/54048880/get-errormessage-from-response-in-netcore-2-2-web-api

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