Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging automatic HTTP 400 responses in .NET Core 6 API

[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.

like image 386
softwareminded Avatar asked Jun 24 '26 00:06

softwareminded


2 Answers

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);
        };
    });
like image 156
Lonli-Lokli Avatar answered Jun 26 '26 14:06

Lonli-Lokli


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/

like image 40
Joaco Ferroni Avatar answered Jun 26 '26 14:06

Joaco Ferroni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!