8
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
[ProducesResponseType(StatusCodes.Status303SeeOther)]
[HttpPost]
[Route("RegisterUsers")]
public async Task<ActionResult<List<UsersInfo>>> RegisterUsers(List<UsersInfo> Users)
{
    // .. how to detect errors here ...
    return Users;
}
 

How do I get errors here specially when API receive wrong format for UserInfo type in the body?

The method implementation never run in the case of wrong userinfo type.

2 Answers 2

7

It depends either it's a Web API or ASP MVC.

Assuming you have Web API, The [ApiController] attribute makes model validation errors automatically trigger an HTTP 400 response. Consequently, the following code is unnecessary in an action method:

    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

The default response type for an HTTP 400 response is ValidationProblemDetails.

In case you need to log such automated responses, you can set the InvalidModelStateResponseFactory to a custom function that first performs the logging and then returns an appropriate BadRequestObjectResult

As an example, you can try to do it like this (see original documentation)

builder.Services.AddControllers()
    .ConfigureApiBehaviorOptions(options =>
    {
      // To preserve the default behaviour, capture the original delegate to call later.
        var builtInFactory = options.InvalidModelStateResponseFactory;

        options.InvalidModelStateResponseFactory = context =>
        {
            var logger = context.HttpContext.RequestServices
                                .GetRequiredService<ILogger<Program>>();

            // Perform logging here.
            // ...

            // Invoke the default behaviour, which produces a ValidationProblemDetails
            // response.
            // To produce a custom response, return a different implementation of 
            // IActionResult instead.
            return builtInFactory(context);
        };
    });
Sign up to request clarification or add additional context in comments.

3 Comments

yes web API - I do like to catch the error and log it to db. "ModelState.IsValid" as you mentioned not necessary but I though if there is any way I could log the bad request
You can set the InvalidModelStateResponseFactory to a custom function that first performs the logging and then returns an appropriate BadRequestObjectResult. learn.microsoft.com/en-gb/dotnet/api/…
I've edit post to include sample & documentation link
1

Well, there are a lot of things you are able to implement. In your case I think you need a kind of Validator to your Endpoint parameters. I suggest to implement something like FluentValidation, so the sender will receive all model errors (if any). Also you can customize the response in that case. Here you can find more about it https://docs.fluentvalidation.net/en/latest/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.