Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get ErrorMessage from Response in Netcore 2.2 Web API

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?

like image 628
Virtus Avatar asked Jan 05 '19 04:01

Virtus


People also ask

How do I return an exception from Web API?

Return InternalServerError for Handled Exceptionscs file and locate the Get(int id) method. Add the same three lines within a try... catch block, as shown in Listing 2, to simulate an error. Create two catch blocks: one to handle a DivideByZeroException and one to handle a generic Exception object.

How does Web API handle global exception in .NET Core?

The middleware UseExceptionHandler can be used to handle exceptions globally. You can get all the details of the exception object (Stack Trace, Inner exception, message etc..) and display them on-screen. You can implement like this.


Video Answer


1 Answers

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.

like image 72
Kirk Larkin Avatar answered Sep 23 '22 01:09

Kirk Larkin