How do I display custom error pages in Asp.Net Mvc 3?

Ahmad picture Ahmad · Jul 18, 2011 · Viewed 30.4k times · Source

I want all 401 errors to be be redirected to a custom error page. I have initially setup the following entry in my web.config.

<customErrors defaultRedirect="ErrorPage.aspx" mode="On">
  <error statusCode="401" redirect="~/Views/Shared/AccessDenied.aspx" />
</customErrors>

When using IIS Express I receive the stock IIS Express 401 error page.

In the event when I do not use IIS Express a blank page is returned. Using Google Chrome's Network tab to inspect the response, I see that while the page is blank a 401 status is returned in the headers

What I have tried thus far is using suggestions from this SO answer since I am using IIS Express but to no avail. I have tried using a combination <custom errors> and <httpErrors> with no luck - the standard error or blank page is still displayed.

The httpErrors section looks like this at the moment based on the link from the above SO question ( I also found another very promising answer however no luck - blank response)

<system.webServer>
  <httpErrors  errorMode="DetailedLocalOnly" existingResponse="PassThrough" >
    <remove statusCode="401"  />
    <error statusCode="401" path="/Views/Shared/AccessDenied.htm" />
  </httpErrors>

 <!-- 
 <httpErrors  errorMode="Custom" 
             existingResponse="PassThrough" 
             defaultResponseMode="ExecuteURL">
      <remove statusCode="401"  />
  <error statusCode="401" path="~/Views/Shared/AccessDenied.htm" 
         responseMode="File" />
 </httpErrors>
 -->
</system.webServer>

I have even modified the applicationhost.config file and modified <httpErrors lockAttributes="allowAbsolutePathsWhenDelegated,defaultPath"> to <httpErrors lockAttributes="allowAbsolutePathsWhenDelegated"> based on information from iis.net. During the course of my endeavours I also managed to stumbled upon this error as described in another SO question.

How do I display custom error pages in Asp.Net Mvc 3?

Additional info

The following controller actions have been decorated with the Authorize attribute for a specific user.

[HttpGet]
[Authorize(Users = "domain\\userXYZ")]
public ActionResult Edit() 
{
   return GetSettings();
}

[HttpPost]
[Authorize(Users = "domain\\userXYZ")]
public ActionResult Edit(ConfigurationModel model, IList<Shift> shifts)
{
    var temp = model;
    model.ConfiguredShifts = shifts;
    EsgConsole config = new EsgConsole();

    config.UpdateConfiguration(model.ToDictionary());
    return RedirectToAction("Index");
}

Answer

ravy amiry picture ravy amiry · Sep 8, 2011

I use these steps:

// in Global.asax.cs:
        protected void Application_Error(object sender, EventArgs e) {

            var ex = Server.GetLastError().GetBaseException();

            Server.ClearError();
            var routeData = new RouteData();
            routeData.Values.Add("controller", "Error");
            routeData.Values.Add("action", "Index");

            if (ex.GetType() == typeof(HttpException)) {
                var httpException = (HttpException)ex;
                var code = httpException.GetHttpCode();
                routeData.Values.Add("status", code);
            } else {
                routeData.Values.Add("status", 500);
            }

            routeData.Values.Add("error", ex);

            IController errorController = new Kavand.Web.Controllers.ErrorController();
            errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
        }

        protected void Application_EndRequest(object sender, EventArgs e) {
            if (Context.Response.StatusCode == 401) { // this is important, because the 401 is not an error by default!!!
                throw new HttpException(401, "You are not authorised");
            }
        }

AND:

// in Error Controller:
    public class ErrorController : Controller {

        public ActionResult  Index(int status, Exception error) {
            Response.StatusCode = status;
            return View(status);
        }

        protected override void Dispose(bool disposing) {
            base.Dispose(disposing);
        }
    }

AND the index view in Error folder:

@* in ~/Views/Error/Index.cshtml: *@

@model Int32    
@{
    Layout = null;
}    
<!DOCTYPE html>    
<html>
<head>
    <title>Kavand | Error</title>
</head>
<body>
    <div>
        There was an error with your request. The error is:<br />
        <p style=" color: Red;">
        @switch (Model) {
            case 401: {
                    <span>Your message goes here...</span>
                }
                break;
            case 403: {
                    <span>Your message goes here...</span>
                }
                break;
            case 404: {
                    <span>Your message goes here...</span>
                }
                break;
            case 500: {
                    <span>Your message goes here...</span>
                }
                break;
            //and more cases for more error-codes...
            default: {
                    <span>Unknown error!!!</span>
                }
                break;
        }
        </p>
    </div>
</body>
</html>

AND -the final step:

<!-- in web.config: -->

<customErrors mode="Off"/>