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]?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With