问题描述
我一直在阅读有关在 ASP.MVC 中执行错误处理的不同方法.我了解控制器中的 try/catch
,以及控制器级别的 [HandleError]
.
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:
这工作正常:
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:
误差模型
namespace My.Models
{
public class ErrorViewModel
{
public string Summary { get; set; }
public string Description { get; set; }
}
}
控制器代码
if(somethingBad){
return View("Error", new ErrorViewModel { Summary = "Summary here", Description = "Detail here" });
}
我的问题是,是否可以从 Global.asax 中重定向到传递 ErrorViewModel
的错误视图,例如
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 });
推荐答案
从 Application_Error 方法中,您可以执行以下操作:
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));
这会将您在此处指定的操作结果的视图返回给用户的浏览器,因此您将需要一个控制器 &返回所需错误视图的操作结果(在本例中为 Error/Error500).它不是重定向,因此在技术上更正确(如果发生错误,您应该立即返回 HTTP 500 状态,而不是像通常那样返回 302 然后返回 500).
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).
此外,如果您想从所有 URL(不仅仅是那些匹配路由的 URL)中捕获所有 404,您可以将以下路由添加到路由配置的末尾
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" });
这篇关于在 MVC 未处理异常上从 Global.asax 重定向到共享错误视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!