2

What I have:

  • A simple Web API - POST api/examples
  • Postman to send the request.

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.