2

I want to show custom error page when user tries to call controller methods which does not exist or authorization error occurs during access in MVC5 web application.

Is there any site which explains how to setup custom error page for MVC5 website.

Thanks in advance

1
  • check this Commented Sep 5, 2014 at 13:06

3 Answers 3

1

Add following <customErrors> tag in the web.config that helps you to redirect to the NotFound action method of Error controller if the system fails to find the requested url (status code 404) and redirects to ServerError action method of error controller if the system fires an internal server error (status code 500)

<!--<Redirect to error page>-->
<customErrors mode="On" defaultRedirect="~/Error/ServerError">
  <error redirect="~/Error/NotFound" statusCode="404" />
</customErrors>
<!--</Redirect to error page>-->

You have to create an Error controller that contains ServerError and NotFound action method that renders the related view to display the proper message to the user.

public class ErrorController : Controller
{
    public ActionResult NotFound()
    {
        return View();
    }
    public ActionResult Error()
    {
        return View();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

You shouldn't redirect on error pages. Using <error redirect="" /> is only permissable if you also have redirectMode="ResponseRewrite"
1

Check out this page by Ben Foster, very detailed explanation of the issues you will encounter and a solid solution. http://benfoster.io/blog/aspnet-mvc-custom-error-pages

Comments

0

if you prefer you can handle errors in globalasax Application_Error() method like this:

protected void Application_Error(object sender, EventArgs e) {
    var exception = Server.GetLastError();
    Response.Clear();

    string redirectUrl = "/Error"; // default
    if (exception is HttpException) {
        if (((HttpException)exception).GetHttpCode() == 404) {
            redirectUrl += "/NotFound";
        } else if (((HttpException)exception).GetHttpCode() == 401) {
            redirectUrl += "/NotAuthorized";
        } else { 
            redirectUrl += "?e=" + ((HttpException)exception).GetHttpCode();
        }
        Server.ClearError();
        Response.Clear();
    }
    Response.Redirect(redirectUrl);
}

Comments

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.