在 .NET Core 6 API 中记录自动 HTTP 400 响应

sof*_*ded 6 .net c# .net-core asp.net-core-webapi

[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;
}
 
Run Code Online (Sandbox Code Playgroud)

特别是当 API 收到正文中 UserInfo 类型的错误格式时,我如何在此处出现错误?

在用户信息类型错误的情况下,该方法实现永远不会运行。

Lon*_*kli 6

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);
    }
Run Code Online (Sandbox Code Playgroud)

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);
        };
    });
Run Code Online (Sandbox Code Playgroud)