How to Customize a Model Validation Response which results in an HTTP 400 Error Code?

94 Points
32 Posts

In .NetCore API project, I'm using following line of code in action to check and throw error:

if (!ModelState.IsValid)
      throw new Exception($"Invalid input model") ;

But seems, it's not reaching to the throw part and returning 400 status code with following api response:

    errors =     {
        Name =         (
            "The Name field is required."
    status = 400;
    title = "One or more validation errors occurred.";
    traceId = "00-19041551252dec44959314a355f38eb7-76202d713d3a0c4f-01";
    type = "";

Is there any way to customize this response model?


Views: 76
Total Answered: 1
Total Marked As Answer: 0
Posted On: 09-Jul-2021 06:05

Share:   fb twitter linkedin
618 Points
84 Posts

As per documentation: automatic-http-400-responses , the [ApiController] attribute makes model validation errors automatically trigger an HTTP 400 response. Consequently, the following code is unnecessary in an action method:

if (!ModelState.IsValid)
      throw new Exception($"Invalid input model") ;


You can disable the automatic 400 behavior by seting the SuppressModelStateInvalidFilter property to true. Add the following code in Startup.ConfigureServices:

services.Configure<ApiBehaviorOptions>(options =>
    options.SuppressModelStateInvalidFilter = true;
Posted On: 13-Jul-2021 00:03
 Log In to Chat