Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Response body is not returning from custom error responses in swagger Swashbuckle

I have integrated swagger to a dot.net core API application using Swashbuckle. When I execute an API via Swagger UI without providing credentials it is returning a "401- Unauthorized" response as expected.

But it is not showing the error response which I have configured to return as a custom error response as the body. It does returns the header as below image.

When I execute the same API via Postman it does return the custom error response as below.

What I need is, I need to see the custom error response body in the swagger UI as well.

In Postman, enter image description here

In Swagger, enter image description here

Same scenario with the 403 and 404 status codes.

like image 283
Darshani Jayasekara Avatar asked Oct 23 '25 04:10

Darshani Jayasekara


1 Answers

After struggling a lot I have found the root cause to the issue.It is due to not having configure the Response Content type in the "app.UseStatusCodePages" middle ware.

  // Custom status handling
        app.UseStatusCodePages(async (StatusCodeContext context) =>
        {
            var settings = new JsonSerializerSettings();
            settings.NullValueHandling = NullValueHandling.Ignore;
            settings.Formatting = Formatting.Indented;

            int statusCode = context.HttpContext.Response.StatusCode;
            ***context.HttpContext.Response.ContentType = "application/json";*** // Added this line to solve the issue

            await context.HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(
                new ErrorResponse((HttpStatusCode)statusCode,
                ReasonPhrases.GetReasonPhrase(statusCode)
                ), settings));
        });

Had to add "context.HttpContext.Response.ContentType = "application/json";" to fix the issue.

like image 115
Darshani Jayasekara Avatar answered Oct 25 '25 21:10

Darshani Jayasekara



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!