Search code examples
asp.net-mvccustom-errorsasp.net-mvc-filters

Custom error page use filter action mvc


My application use MVC4, Entity Framework 6. I want custom Actions return to page error (500, 404, 403) when an error occurs use Filter Action on MVC.

Currently, I'm using Application_Error method in file Global.asax to return page error, but it not working when action call from AJAX.

Ex:

This is page

[ExecuteCustomError]
public ActionResult TestAction()
{
    Rerurn View();
}

This is view returned after AJAX call

[ExecuteCustomError]
public ActionResult ReturnView()
{
    //If return error code, i have return message error here.
    return PartialView();
}

Solution

  • Looks like you haven't provided correct path of your error page. Like you need to add your error page in shared view folder then you can access this page. If your page is in the other folder then you have to specify the correct path of your error view page. Like below :

    return PartialView("~/Views/ErrorPartialView.cshtml", myModel);

    We have other options to call error page through web. In Config file you can do the below settings :

    <configuration> ... <system.webServer> ... <httpErrors errorMode="Custom" existingResponse="Replace"> <clear /> <error statusCode="400" responseMode="ExecuteURL" path="/ServerError.aspx"/> <error statusCode="403" responseMode="ExecuteURL" path="/ServerError.aspx" /> <error statusCode="404" responseMode="ExecuteURL" path="/PageNotFound.aspx" /> <error statusCode="500" responseMode="ExecuteURL" path="/ServerError.aspx" /> </httpErrors> ... </system.webServer> ... </configuration>

    Here we go for Global Exception Filter :

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace MVCGlobalFilter.Filters
    {
        public class ExecuteCustomErrorHandler : ActionFilterAttribute, IExceptionFilter
        {
            public void OnException(ExceptionContext filterContext)
            {
                Exception e = filterContext.Exception;
                filterContext.ExceptionHandled = true;
                filterContext.Result = new ViewResult()
                {
                    ViewName = "CommonExceptionPage"
                };
            }
        }
    }
    

    Now you have to register your ExecuteCustomErrorHandler class in Global.asax file :

    /// <summary>
    /// Application start event
    /// </summary>
    protected void Application_Start()
    {
           AreaRegistration.RegisterAllAreas();
           FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
           RouteConfig.RegisterRoutes(RouteTable.Routes);
           BundleConfig.RegisterBundles(BundleTable.Bundles);
           log4net.Config.XmlConfigurator.Configure();
    
           // Calling Global action filter
           GlobalFilters.Filters.Add(new ExecuteCustomErrorHandler());
    }
    

    You need to add CommonExceptionPage view in Shared folder :

    CommonExceptionPage.cshtml :

    @{
        ViewBag.Title = "Execute Custom Error Handler";
    }
    
    <hgroup class="title">
        <h1 class="error">Error.</h1>
        <h2 class="error">An error occurred while processing your request.</h2>
    </hgroup>