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

Santosh Karanam
  • 1,077
  • 11
  • 23
  • check [this](http://stackoverflow.com/questions/10928277/redirect-to-another-page-when-user-is-not-authorized-in-asp-net-mvc3) – szpic Sep 05 '14 at 13:06

3 Answers3

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();
    }
}
Hiren Kagrana
  • 912
  • 8
  • 21
  • 1
    You shouldn't redirect on error pages. Using `` is only permissable if you also have `redirectMode="ResponseRewrite"` – Dai Feb 20 '15 at 18:40
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

Alex Stephens
  • 3,017
  • 1
  • 36
  • 41
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);
}
phoe
  • 90
  • 8