Monday 21 December 2015

application_error redirect to error page mvc

Handling the error getting in MVC application into Application_Error method in Global.asax page. So whatever the error you will get into application it will work as you handle there.

If getting any application error it will log that error.
If getting 404 it will redirect to particular controller/action like PageNotFound
If getting other than 404 it will redirect to particular controller/action like Index




protected void Application_Error(object sender, EventArgs e)
        {
            var exception = Server.GetLastError(); /// Getting the server last error
            var statuscode = Response.StatusCode; /// Getting the response Status code it will 404, 401, 500 etc.
           
            /*********** Write a code to log that error either in eventviewr or DB **********************/

            Server.ClearError();
            var routeData = new RouteData();
            routeData.Values["controller"] = "Error";

            ///// Checking the status code and based on it will redirect to particular controller and action.
            if (statuscode != 404)
            {
                routeData.Values["action"] = "Index";
            }
            else if (statuscode == 404)
            {
                routeData.Values["action"] = "PageNotFound";
            }          
            Response.TrySkipIisCustomErrors = true;
            IController errorsController = new ErrorController();
            HttpContextWrapper wrapper = new HttpContextWrapper(Context);
            var rc = new System.Web.Routing.RequestContext(wrapper, routeData);
            errorsController.Execute(rc);


        }

No comments:

Post a Comment