4

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)?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, could explain how each part of the highlighted code is working to handle 404 / 500 / 401 errors?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.