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

前端 未结 1 1662
既然无缘
既然无缘 2021-01-20 16:48

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

1条回答
  •  说谎
    说谎 (楼主)
    2021-01-20 17:14

    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" });
    

    0 讨论(0)
提交回复
热议问题