Pok*_*oku 17 asp.net error-handling asp.net-mvc
我想在我的MVC项目中使用Application_Error,但我不能让它工作.我将以下内容添加到我的Global.asax文件中:
protected void Application_Error(object sender, EventArgs e)
{
Exception objErr = Server.GetLastError().GetBaseException();
Session["Test"] = "Message:" + objErr.Message.ToString();
}
Run Code Online (Sandbox Code Playgroud)
(会话仅用于测试.我将使用数据库记录错误,如果我让它工作.)然后我尝试从我的HomeController和我的Home/Index视图抛出异常,但它只触发调试.
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
throw (new Exception());
return View();
}
Run Code Online (Sandbox Code Playgroud)
在我的Webconfig文件中,我设置了一个defaulterror页面,但它没有重定向到视图:
<customErrors defaultRedirect="Home/Error">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
Run Code Online (Sandbox Code Playgroud)
blo*_*art 17
首先要记住,全局错误处理应该是最后的手段,并且控制器类具有错误的特定错误方法;
protected virtual bool OnError(string actionName,
System.Reflection.MethodInfo methodInfo, Exception exception)
Run Code Online (Sandbox Code Playgroud)
在此范围内,您可以重定向到标准共享错误视图;
protected override bool OnError(string actionName,
System.Reflection.MethodInfo methodInfo, Exception exception)
{
RenderView("Error", exception);
return false;
}
Run Code Online (Sandbox Code Playgroud)
您在全局应用程序错误中遇到的问题是它没有视图或控制器的概念,因此如果您想在那里重定向,那么您必须使用已知的URL
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
System.Diagnostics.Debug.WriteLine(exception);
Response.Redirect("/Home/Error");
}
Run Code Online (Sandbox Code Playgroud)
但你不需要这样做.如果在web.config中设置默认错误页面,则不需要该重定向
<customErrors defaultRedirect="Home/Error" />
Run Code Online (Sandbox Code Playgroud)
但是,除非您已将错误视图添加到不存在的Home控制器,因此请将以下内容添加到主控制器
public ActionResult Error()
{
return View();
}
Run Code Online (Sandbox Code Playgroud)
然后(如果你是明智的)你将错误处理代码放在Error()方法中,因为所有未处理的错误都将结束.
public ActionResult Error()
{
Exception exception = Server.GetLastError();
System.Diagnostics.Debug.WriteLine(exception);
return View();
}
Run Code Online (Sandbox Code Playgroud)
最后请记住,默认情况下,如果要连接到localhost,则不会看到自定义错误!所以你需要改变这种行为
<customErrors mode="On" defaultRedirect="/Home/Error" />
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
48204 次 |
| 最近记录: |