2

I have error 400 and 404 pages that I have created and want to use it for my application. I have declared this in my Startup.cs:

app.UseStatusCodePages(async context => {
    if(context.HttpContext.Response.StatusCode == 400)
    {
        context.HttpContext.Response.Redirect("~/Views/Shared/Errors/AccessDenied.cshtml");
    }
});
app.UseStatusCodePages(async context => {
    if (context.HttpContext.Response.StatusCode == 404)
    {
        context.HttpContext.Response.Redirect("~/Views/Shared/Errors/NotFound.cshtml");
    }
});

Is this correct? When I tested it, I still get redirected back to the standard .net core error page.Am I missing something else?

2
  • May be cause you are getting 500 Status code and not 400/404 Commented Jun 24, 2019 at 9:44
  • I'm getting a 404. The way I get it is from a link www.app.com/user/abcd1234 Commented Jun 24, 2019 at 9:50

1 Answer 1

2

First of all, you can combine both using an if .. else construct like

app.UseStatusCodePages(async context => {
    if(context.HttpContext.Response.StatusCode == 400)
    {
        context.HttpContext.Response.Redirect("~/Views/Shared/Errors/AccessDenied.cshtml");
    }
    else if (context.HttpContext.Response.StatusCode == 404)
    {
        context.HttpContext.Response.Redirect("~/Views/Shared/Errors/NotFound.cshtml");
    }
});

Second, make sure you call UseStatusCodePages middleware before request handling middleware (for example, Static File Middleware and MVC Middleware).

I would suggest you to use either UseStatusCodePagesWithRedirect (OR) UseStatusCodePagesWithReExecute instead redirecting explicitly

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

1 Comment

Hi! Thanks for your answer. However, I am getting this url now when the error 404 happens. localhost:44365/Messages/AnnouncementAttachments/~/Views/Shared/…

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.