Get ErrorMessage from Response in Netcore 2.2 Web API

Virtus picture Virtus · Jan 5, 2019 · Viewed 8.3k times · Source

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?

Answer

Kirk Larkin picture Kirk Larkin · Jan 5, 2019

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.