How to implement MVC custom error pages.

In this article, we will learn about how to implement MVC custom error page. Very common errors of MVC application as listed below:
Not Found: Whenever page is not found (MVC 404 Page).
Access Denied: Whenever we are trying to access folder (CAS Code Access Security) permissions or someone like same.
Internal Server Error: This error is related to internal server error.
Error Occurred: If any other error occurred in our MVC application.


In Global.asax
using customerrorpage.Controllers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;


namespace customerrorpage
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
           

        }


        protected void Application_Error(object sender, EventArgs e)
        {
            var httpContext = ((MvcApplication)sender).Context;
            var currentController = " ";
            var currentAction = " ";
            var currentRouteData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));

            if (currentRouteData != null)
            {
                if (currentRouteData.Values["controller"] != null && !String.IsNullOrEmpty(currentRouteData.Values["controller"].ToString()))
                {
                    currentController = currentRouteData.Values["controller"].ToString();
                }

                if (currentRouteData.Values["action"] != null && !String.IsNullOrEmpty(currentRouteData.Values["action"].ToString()))
                {
                    currentAction = currentRouteData.Values["action"].ToString();
                }
            }

            var ex = Server.GetLastError();
            var controller = new ErrorController();
            var routeData = new RouteData();
            var action = "Index";

            if (ex is HttpException)
            {
                var httpEx = ex as HttpException;

                switch (httpEx.GetHttpCode())
                {
                    case 404:
                        action = "NotFound";
                        break;

                    case 401:
                        action = "AccessDenied";
                        break;

                    case 500:
                        action = "InternalServerError";
                        break;
                }
            }

            httpContext.ClearError();
            httpContext.Response.Clear();
            httpContext.Response.StatusCode = ex is HttpException ? ((HttpException)ex).GetHttpCode() : 500;
            httpContext.Response.TrySkipIisCustomErrors = true;

            routeData.Values["controller"] = "Error";
            routeData.Values["action"] = action;

            controller.ViewData.Model = new HandleErrorInfo(ex, currentController, currentAction);
            ((IController)controller).Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData));
        }

   
    }
}

In ErrorController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace customerrorpage.Controllers
{

    public class ErrorController : Controller
    {
    
        [HttpGet]
        public ActionResult Index()
        {
            TempData["error"] = "Error Occurred!";
            return View();
        }
   


        public ActionResult NotFound()
        {
            TempData["error"] = "Page not Found";
            return View();
        }
      
        [HttpGet]
        public ActionResult AccessDenied()
        {
            TempData["error"] = "Access Denied";
            return View("Index");
        }

        [HttpGet]
        public ActionResult InternalServerError()
        {
            TempData["error"] = "Internal Server Error";
            return View("Index");
        }
    }
}
In View.cshtml
@{
    ViewBag.Title = @TempData["error"];
    Layout = null;
}

<div id="wrapper">
    <div id="page-wrapper">
        <div class="row">
            <div class="col-lg-13">

                <div class="panel-heading">
                    <h2 class="page-header">
                        Error!
                    </h2>
                </div>
                <div class="panel-body">
                    <div>
                        <h4>
                            Error:
                        </h4>
                        @TempData["error"]
                    </div>
                    <div>
                        <h4>
                            Error Description:
                        </h4>
                        <div class="alert alert-warning">
                            @Model.Exception.Message.ToString() @Html.Raw(" ") @Model.ControllerName @Html.Raw(" ") @Model.ActionName
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>
</div>

Out-Put:-



How to implement MVC custom error pages. How to implement MVC custom error pages. Reviewed by NEERAJ SRIVASTAVA on 11:21:00 PM Rating: 5

No comments:

Powered by Blogger.