Hi @Mr Edge
How to catch WebAPI Core unauthenticated status
You can try to use the UseStatusCodePages
middleware to capture the http response and format the returned error message. Code like this:
app.UseStatusCodePages(async statusCodeContext =>
{
switch (statusCodeContext.HttpContext.Response.StatusCode)
{
case 401:
statusCodeContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
await statusCodeContext.HttpContext.Response.WriteAsJsonAsync(new ErrorMessage { httpStatus = 500, Message = "some message" });
////If you want to return a html page, use the following code:
//statusCodeContext.HttpContext.Response.ContentType = "text/html";
//await statusCodeContext.HttpContext.Response.WriteAsync("<html lang=\"en\"><body>\r\n");
//await statusCodeContext.HttpContext.Response.WriteAsync("401 ERROR From API!<br><br>\r\n");
//await statusCodeContext.HttpContext.Response.WriteAsync( "<a href=\"/\">Home</a><br>\r\n");
//await statusCodeContext.HttpContext.Response.WriteAsync("</body></html>\r\n");
break;
case 403:
statusCodeContext.HttpContext.Response.StatusCode = 400;
await statusCodeContext.HttpContext.Response.WriteAsJsonAsync(new ErrorMessage { httpStatus = 500, Message = "some message" });
break;
}
});
Then, when using Postman to access the endpoint without token, the result as below:
More detail information about using UseStatusCodePages, see Handle errors in ASP.NET Core
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion