Home > Enterprise >  Logging automatic HTTP 400 responses in .NET Core 6 API
Logging automatic HTTP 400 responses in .NET Core 6 API

Time:11-18

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

CodePudding user response:

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

CodePudding user response:

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/

  • Related