In my startup I have added this code:
app.UseStatusCodePagesWithReExecute("/Home/Error", "?statusCode={0}");
app.UseMiddleware<ExceptionHandlingMiddleware>();
In my controller I have added:
[AllowAnonymous]
public IActionResult Error(int? statusCode = null)
{
return View(new ErrorViewModel {
RequestId = Activity.Current?.Id ??
HttpContext.TraceIdentifier,
StatusCode = statusCode
});
}
And I also have this middleware class for catching 500's:
public class ExceptionHandlingMiddleware
{
private readonly RequestDelegate _next;
public ExceptionHandlingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception)
{
context.Response.Clear();
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
}
}
}
I can catch 404's and 500. Everything else comes back as 404 (including 401). If I debug, the statusCode in the Error action is always 404.
How can I get the statusCode to reflect the reality (i.e. 401)?
You can check my code here .It's global handle exception so you can catch 401 exception but I think you need to throw error code in order for global handler exception catch 401 error code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With