エラーが発生するたびに、C#.net mvc アプリケーションの Application_Error() が 2 回呼び出されます。
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));
}