Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]?

like image 414
Ian Vink Avatar asked Oct 27 '25 04:10

Ian Vink


1 Answers

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.

like image 69
Maxime Poulain Avatar answered Oct 29 '25 17:10

Maxime Poulain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!