Reputation: 741
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.
Same scenario with the 403 and 404 status codes.
Upvotes: 4
Views: 2052
Reputation: 741
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.
Upvotes: 5