'ASP.NET Core 6 ExceptionMiddleware and Validations
In ASP.NET Core 6, I have a custom middleware that handles exceptions returning a specific structure:
services.AddControllers(options => options.Filters.Add(typeof(CustomHttpResponseExceptionFilter)));
Works nicely. However, when an argument fails a param validation like:
GetSomethingAsync([Required][MinLength(2)]string orderNumber)
the CustomHttpResponseExceptionFilter isn't called.
Where can I intercept a failure for e.g. data annotation [Required]?
Solution 1:[1]
Hello you need to customize the behavior of ModelStateInvalidFilter.
To do so, you can achieve that doing the following in your Program.cs
builder.Services.AddControllers().ConfigureApiBehaviorOptions(options =>
{
options.InvalidModelStateResponseFactory = context =>
{
// Expects an instance of IActionResult.
};
});
You will find more information at Microsoft's documentation.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Maxime Poulain |
