我的C#.net mvc应用程序每当发生任何错误时,都会调用两次Application_Error()。
Application_Error()的代码是:
protected void Application_Error(object sender, EventArgs e)
{
var httpContext = ((MvcApplication)sender).Context;
//var currentController = " ";
//var currentAction = " ";
string currentController;
string currentAction;
var currentRouteData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));
currentController = "";
currentAction = "";
if (currentRouteData != null)
{
if (currentRouteData.Values["controller"] != null && !String.IsNullOrEmpty(currentRouteData.Values["controller"].ToString()))
{
currentController = currentRouteData.Values["controller"].ToString();
}
if (currentRouteData.Values["action"] != null && !String.IsNullOrEmpty(currentRouteData.Values["action"].ToString()))
{
currentAction = currentRouteData.Values["action"].ToString();
}
}
var ex = Server.GetLastError();
var controller = new ErrorController();
var routeData = new RouteData();
var action = "Error";
if (ex is HttpException)
{
var httpEx = ex as HttpException;
switch (httpEx.GetHttpCode())
{
case 400:
action = "BadRequest";
break;
case 401:
action = "Unauthorized";
break;
case 403:
action = "Forbidden";
break;
case 404:
action = "NotFound";
break;
case 408:
action = "RequestTimeout";
break;
case 500:
action = "InternalServerError";
break;
case 502:
action = "BadGateway";
break;
case 503:
action = "ServiceUnavailable";
break;
case 504:
action = "GatewayTimeout";
break;
}
}
httpContext.ClearError();
httpContext.Response.Clear();
httpContext.Response.StatusCode = ex is HttpException ? ((HttpException)ex).GetHttpCode() : 500;
httpContext.Response.TrySkipIisCustomErrors = true;
routeData.Values["controller"] = "Error";
routeData.Values["action"] = action;
controller.ViewData.Model = new HandleErrorInfo(ex, currentController, currentAction);
((IController)controller).Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData));
}
答案 0 :(得分:4)
我猜您的浏览器正在向错误页面上的/favicon.ico
文件发送一个自动请求,您忘记将该图标包含在您的应用程序中,并且分别针对404触发Application_Error事件。您可以通过在Application_Error方法中放置断点并分析以下值来查看有关请求的更多详细信息:
httpContext.Request.Url.AbsoluteUri
我把我的2¢看作是http://localhost:1234/favicon.ico
。