我想在我的MVC项目中使用Application_Error,但是我无法使其正常工作。我将以下内容添加到我的Global.asax文件中:
protected void Application_Error(object sender, EventArgs e)
{
Exception objErr = Server.GetLastError().GetBaseException();
Session["Test"] = "Message:" + objErr.Message.ToString();
}
(该 session 仅用于测试。如果我可以使用该数据库,我将使用数据库记录错误。)
然后,我尝试从HomeController和Home/Index View 中引发异常,但它只会触发Debug。
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
throw (new Exception());
return View();
}
在我的Webconfig文件中,我设置了defaulterror页面,但它不会重定向到 View :
<customErrors defaultRedirect="Home/Error">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
最佳答案
因此,首先请记住,全局错误处理应该是最后的选择,并且 Controller 类具有针对错误的特定错误方法;
protected virtual bool OnError(string actionName,
System.Reflection.MethodInfo methodInfo, Exception exception)
您可以在其中重定向到标准共享错误 View ;
protected override bool OnError(string actionName,
System.Reflection.MethodInfo methodInfo, Exception exception)
{
RenderView("Error", exception);
return false;
}
您在全局应用程序错误中遇到的问题是它没有 View 或 Controller 的概念,因此,如果要在其中进行重定向,则必须使用已知的URL
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
System.Diagnostics.Debug.WriteLine(exception);
Response.Redirect("/Home/Error");
}
但您不需要这样做。如果您在web.config中设置默认错误页面,则不需要该重定向
<customErrors defaultRedirect="Home/Error" />
但是,除非您向Home Controller 添加了不存在的错误 View ,否则将以下内容添加到Home Controller
public ActionResult Error()
{
return View();
}
然后(如果您很明智)将错误处理代码放在Error()方法中,因为这是所有未处理的错误将最终结束的地方。
public ActionResult Error()
{
Exception exception = Server.GetLastError();
System.Diagnostics.Debug.WriteLine(exception);
return View();
}
最后要记住,默认情况下,如果您连接到本地主机,则不会看到自定义错误!所以你需要改变这种行为
<customErrors mode="On" defaultRedirect="/Home/Error" />
关于asp.net - 如何在ASP.NET MVC中使用Application_Error?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1464531/