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

做~自己de王妃 提交于 2019-12-02 00:31:59
Carl

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