How to change the error response body for ASP.NET Core Web API and NSwag

64 Views Asked by At

I am using .NET Core 8.0, Newtonsoft json and NSwag to generate a Web API server. We have a custom json error body response we use for errors.

That works fine when we generate the error.

However, if the json body request has a syntax error in it, the framework (I'm not sure which bit) automatically generates a 400 response with an error message in a different format than what we specified in the OpenAPI spec.

I have tried ExceptionMiddleware. I was expecting to catch the exception in that handler, but all I see is the error response in the HttpContext, built and ready to reply.

Any thoughts? Is there a place I can add my own handler?

2

There are 2 best solutions below

0
Ian Kemp On

automatically generates a 400 response with an error message in a different format than what we specified in the OpenAPI spec

You are probably seeing a ProblemDetails response. As the linked article explains, this is an internet-standard format for representing an error response due to an invalid request.

By default, any controller decorated with ApiControllerAttribute is automatically opted in to ProblemDetails handling. There are many ways to control and customise this handling, all covered in that article, but if you just want to disable it completely the following in your Program.cs should do the trick:

builder.Services.AddControllers()
    .ConfigureApiBehaviorOptions(options =>
    {
        options.SuppressMapClientErrors = true;
    });

I would strongly suggest that you take the time to read that article and understand how you can leverage this functionality to automatically return your own consistent error responses, as opposed to manually generating those responses in each and every controller endpoint.

0
Rena On

If your project is Web Api and the controllers are declared with [ApiController] attribute, be sure set SuppressModelStateInvalidFilter true to disable automatic model validation in Program.cs file:

builder.Services.AddControllers().ConfigureApiBehaviorOptions(options =>
{
    options.SuppressModelStateInvalidFilter = true; // Disable automatic model validation
});