In order to generate a complete swagger.json file, I specify all possible return statuses for my minimal .NET API methods, which look like this:
app.MapGet(rootPattern, async (MyDbContext db) =>
{
return await db.Something.Where(x => x.SomeCondition).ToListAsync();
})
.Produces(200)
.Produces(401)
.RequireAuthorization();
However, this will now specify a 401 result as having a content type of application/json
, while in reality, .NET does not set Content-Type (and returns no content) when the request is unauthorized. (A side effect is that our testing suite (ApiDog) will always mark the request as Failed because the Content-Type does not match the expected value).
I can do this .Produces(401, typeof(string), "text/plain")
, which is somewhat better and satisfies ApiDog, but still not quite correct.
So my question is: Can I specify a 401 response without Content-Type? Or alternatively, can I configure my app in a way so that a 401 has some kind of json response (e.g. { "status":"401" }
)
Or alternatively, can I configure my app in a way so that a 401 has some kind of json response (e.g. { "status":"401" })
You could add a middleware as below:
app.Use(async (context, next) =>
{
await next.Invoke();
if (context.Response.StatusCode == 401)
{
await context.Response.WriteAsJsonAsync(new ResponseModel() { statuscode=401});
}
});
app.UseAuthentication();
app.UseAuthorization();
....
app.Map(....)
Result: