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