MrJahanbin
MrJahanbin

Reputation: 465

how to handle bad request web api core with custome message?

I have a similar problem. Is there a simpler way to handle the input data type errors?

https://coderethinked.com/customizing-automatic-http-400-error-response-in-asp-net-core-web-apis/

I searched but found no answer.

Update:

I found a solution from Microsoft's example:       

 return BadRequest (new {message = "Something went wrong"});

But When field is in [Required] model, error 400 is called before running the service. Is there a way to resolve the 400 error from the handle model?

Upvotes: 0

Views: 2552

Answers (1)

Ryan
Ryan

Reputation: 20106

But When field is in [Required] model, error 400 is called before running the service. Is there a way to resolve the 400 error from the handle model?

The [ApiController] attribute makes model validation errors automatically trigger an HTTP 400 response.

To disable the automatic 400 behavior, set the SuppressModelStateInvalidFilter property to true in Startup.ConfigureServices:

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

Refer to https://learn.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-3.1#disable-automatic-400-response

Upvotes: 5

Related Questions