Skip to main content

Custom error page in MVC 4

MVC 4 project has already has an Error.cshtml in Views\Shared folder. In order to use the Error.cshtml, you have to do following steps:

1. Set the customError mode to On inside web.config file under <system.web> element
<customErrors mode="On" />
2. In the FilterConfig.cs file inside App_Start folder, make sure the filters.Add(new HandleErrorAttribute()) is there.

    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }
    }
3. Edit Error.cshtml inside \Views\Shared folder to show error message
@model System.Web.Mvc.HandleErrorInfo

@{
    ViewBag.Title = "Error";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div>An error has occurred</div>
@if (Model != null && HttpContext.Current.IsDebuggingEnabled)
{
    <div>
       <p>
            <b>Exception:</b> @Model.Exception.Message<br />
            <b>Controller:</b> @Model.ControllerName<br />
            <b>Action:</b> @Model.ActionName
        </p>
        <div style="min-height: 400px;overflow:auto">
            <pre>
                  @Model.Exception.StackTrace
            </pre>
         </div>
      </div>
}
else
{
    <p>@Model.Exception.Message</p>
}
4. The system will show the Error page in the following conditions:
    1) When there is uncaught Exceptions, the system will automatically call this Error view and pass the Exception information
    2) You can manually redirect to this view in your error handling code:
        protected ActionResult GotoErrorPage(string strErrorMessage)
        {
            string controller = this.ControllerContext.RouteData.Values["controller"].ToString();
            string action = this.ControllerContext.RouteData.Values["action"].ToString();
            return View("Error", new HandleErrorInfo(new System.Exception(strErrorMessage)), controller, action));
        }

5. If you want to create your own customized error page for HTTP status code 401, 404 etc, you need add more <error redirect /> configuration inside <customErrors> element inside web.config file. However, you need to create your own ErrorController and error views to handle different situation.

Comments

Popular posts from this blog

X509Certificate2: The system cannot find the file specified.

When I use the new X509Certificate2(fileName, password, X509KeyStorageFlags.DefaultKeySet) to create certificate from certificate file containing private key in my web application, I got following error message: System . Security . Cryptography . CryptographicException : The system cannot find the file specified . at System . Security . Cryptography . CryptographicException . ThrowCryptogaphicException ( Int32 hr ) at System . Security . Cryptography . X509Certificates . X509Utils . _LoadCertFromBlob ( Byte [] rawData , IntPtr password , UInt32 dwFlags , Boolean persistKeySet , SafeCertContextHandle & pCertCtx ) at System . Security . Cryptography . X509Certificates . X509Certificate . LoadCertificateFromBlob ( Byte [] rawData , Object password , X509KeyStorageFlags keyStorageFlags ) at System . Security . Cryptography . X509Certificates . X509Certificate2 .. ctor ( Byte [] rawData , String password , X509KeyStorageFlags keyStorageFlags ) In orde...

Forms authentication ReturnUrl strange behavior and fix

When working with .NET forms authentication, I have found a strange behavior: For example, we have a web site using form based authentication. There are only two pages in the site: login.aspx and default.aspx. Default.aspx is the protected page. Without login to the site, if you type directly the URL to the default.aspx page with ReturnUrl as QueryString like this: http://localhost/YourWebApp/Default.aspx?ReturnUrl=Default.aspx Instead of redirect you to the login.aspx page, you will directly get http unauthorized error (401.2). However, if you remove the ReturnUrl query string or change it to something else, you will get expected behavior: redirect to login.aspx page. It seems .NET has some special treatment to ReturnUrl parameter. In order to fix this, we need to intercept the 401 response before it sends to client and redirect user to login.aspx page. In global.asax page, we need to add this event handler:         protected void Applica...

Manage IIS 7 remotely using PowerShell and AppCmd

We can use  Windows PowerShell remoting features  to manage IIS 7 websites remotely.  Currently, remoting is supported on Windows Vista with Service Pack 1 or later, Windows 7, Windows Server 2008, and Windows Server 2008 Release 2.  Start Windows PowerShell as an administrator by right-clicking the Windows PowerShell shortcut and selecting Run As Administrator .  Enable PowerShell Remoting with Enable-PSRemoting -Force Starting a Remote Session using:  Enter-PSSession -ComputerName <COMPUTER> -Credential <USER> Now the PowerShell connected to the remote server. Any commands issued with work against the remote server. We can use the Appcmd.exe command line tool to manage remote server just as what we do locally. For example, to add an application pool: c:\windows\system32\inetsrv\appcmd add apppool /name:"Contoso" /managedPipelineMode:Integrated /managedRuntimeVersion:"v4.0" /enable32BitAppOnWin64:true To change application p...