Global.asax 中的 ASP.NET MVC Application_Error 处理程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16884074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET MVC Application_Error handler in Global.asax
提问by sevenmy
In Global.asax we have a class of type System.Web.HttpApplication named MvcApplication that represents the application and in which we can handle various events.
在 Global.asax 中,我们有一个名为 MvcApplication 的 System.Web.HttpApplication 类型的类,它代表应用程序,我们可以在其中处理各种事件。
I'm interested in the Application_Error handler. In this handler we can use all the properties of the class MvcApplication.
我对 Application_Error 处理程序感兴趣。在这个处理程序中,我们可以使用类 MvcApplication 的所有属性。
-1-
-1-
Is always true that '(MvcApplication)sender' and 'this' are the same object?
'(MvcApplication)sender' 和 'this' 是同一个对象总是正确的吗?
protected void Application_Error(object sender, EventArgs e)
{
var httpApp = (MvcApplication)sender;
var equality1 = httpApp == this; // always true?
}
-2-
-2-
What is the best way to get the error? The following examples return the same error?
获得错误的最佳方法是什么?以下示例返回相同的错误?
Exception ex0 = this.Context.Error;
Exception ex1 = httpContext.Error;
Exception ex2 = Server.GetLastError();
var equality3 = ex1 == ex2; // true?
回答by Swapnil Malap
Global.asax
全球.asax
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Response.Clear();
if (exception != null)
{
Common.WriteErrorLog(exception);
}
HttpException httpException = exception as HttpException;
if (httpException != null)
{
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");
switch (httpException.GetHttpCode())
{
case 404:
// page not found
routeData.Values.Add("action", "HttpError404");
break;
case 500:
// server error
routeData.Values.Add("action", "HttpError500");
break;
default:
routeData.Values.Add("action", "Index");
break;
}
routeData.Values.Add("error", exception.Message);
// clear error on server
Server.ClearError();
Response.RedirectToRoute(routeData.Values);
// at this point how to properly pass route data to error controller?
//Response.Redirect(String.Format("~/Error/{0}/?message={1}", "Index", exception.Message));
}
}
Controller :
控制器 :
public class ErrorController : Controller
{
// GET: Error
public ActionResult Index(string error="")
{
ViewBag.Message = error;
return View();
}
public ActionResult HttpError404(string error = "")
{
ViewBag.Message = error;
return View();
}
public ActionResult HttpError500(string error = "")
{
ViewBag.Message = error;
return View();
}
}

