dvc.junior
dvc.junior

Reputation: 352

Handle invalid requests errors in .net core 2.1 web api

What I have:

When I make the request with the content type set as application/json everything works just fine. But when I change to anything else I get the following response:

{
    "": [
        "The input was not valid."
    ]
}

From Kestrel logs I get:

the application completed without reading the entire request body.

This is how the web api is handling invalid requests. What I want to find out is how can I capture and handle this kind of exception and change the default message.

I do have a error handling middleware, but in this scenario the request is invalid, so it's never called.

How can I change this default behavior?

Upvotes: 2

Views: 1443

Answers (1)

dvc.junior
dvc.junior

Reputation: 352

Well, after some while, I had to come back to this issue.

I've find out that this validation has to do with the automatic model state validation of the ASP.NET Core Framework. So everytime a invalid value is passed to the web API controller, a filter, the ModelStateInvalidFilter, is executed prior and ends up firing the 400 bad request: "The input was not valid."

Although there are some ways to override this behavior, for my case, I found it best to just disable it. To do so just add the following lines to your Startup.cs in the ConfigureServices method:

services.Configure<ApiBehaviorOptions>(options =>
{
    options.SuppressModelStateInvalidFilter = true;
});

More details about this and how to override it, you can check here:

http://www.talkingdotnet.com/disable-automatic-model-state-validation-in-asp-net-core-2-1/

and here:

Correct way to disable model validation in ASP.Net Core 2 MVC

Upvotes: 1

Related Questions