Redirect to shared Error view from Global.asax on MVC unhandled exception

半腔热情 提交于 2019-12-02 03:16:21

问题


I've been reading about the different ways to perform error handling in ASP.MVC. I know about try/catch within a controller, and also about [HandleError] at controller-level.

However, I am trying to perform global error handling for unhandled exceptions that could occur anywhere in the application (the wow - we never expected a user to do that! type of thing). The result of this is that an email is sent to dev's:

This is working fine:

protected void Application_Error()
{
    Exception last_ex = Server.GetLastError();
    Server.ClearError();
    // send email here...
    Response.Redirect("/Login/Login");
}

Elsewhere in the application, should an error occur in a controller, we have this logic which provides a friendly error in our error view:

Error Model

namespace My.Models
{
    public class ErrorViewModel
    {
        public string Summary { get; set; }
        public string Description { get; set; }
    }
}

Controller Code

if(somethingBad){
    return View("Error", new ErrorViewModel { Summary = "Summary here", Description = "Detail here" });
}

My question is, is it possible to redirect to the error view passing the ErrorViewModel from within Global.asax, e.g.

// send email here...
Response.MethodToGetToView(new ErrorViewModel { Summary = "Error", Description = ex.Message });

回答1:


From the Application_Error method, you can do something like:

RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("action","Error500");
routeData.Values.Add("Summary","Error");
routeData.Values.Add("Description", ex.Message);
IController controller = new ErrorController()
controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));

This will return the view from the action result you specify here to the user's browser, so you will need a controller & action result that returns your desired error view (Error/Error500 in this example). It is not a redirect so is technically more correct (if an error occurs, you should return an HTTP 500 status immediately, not a 302 then a 500 as is often done).

Also, if you want to capture all 404's from all URLs (not just those that match a route), you can add the following route to the end of your route config

routes.MapRoute("CatchAllUrls", "{*url}", new { controller = "Error", action = "Error404" }, new string[] { "MyApp.Controllers" });


来源:https://stackoverflow.com/questions/25721554/redirect-to-shared-error-view-from-global-asax-on-mvc-unhandled-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!