我做了類似maxlego處理所有錯誤(不只是那些發生在與HandleError屬性的控制器中)。
我MvcApplication類(在的global.asax.cs)具有這樣的:
public class MvcApplication : HttpApplication
{
// usual stuff here...
protected void Application_Error(object sender, EventArgs e)
{
Server.HandleError(((MvcApplication)sender).Context);
}
}
上面的代碼使用擴展方法從有用的東西我的MVC庫。有了這個,我不需要任何錯誤處理屬性,customErrors配置或自定義過濾器。相反,擴展方法將記錄錯誤的詳細信息,然後調用相應的視圖,或者:
- 存取遭拒
- NOTFOUND
- InternalServerError
擴展方法的代碼,使這項工作是:
public static class HttpServerUtilityExtensions
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
public static void HandleError(this HttpServerUtility server, HttpContext httpContext)
{
var currentController = " ";
var currentAction = " ";
var currentRouteData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));
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 exception = server.GetLastError();
Logger.ErrorException(exception.Message, exception);
var controller = DependencyResolver.Current.GetService<ErrorController>();
var routeData = new RouteData();
var action = "InternalServerError";
if (exception is HttpException)
{
var httpEx = exception as HttpException;
switch (httpEx.GetHttpCode())
{
case 404:
action = "NotFound";
break;
case 401:
action = "AccessDenied";
break;
}
}
httpContext.ClearError();
httpContext.Response.Clear();
httpContext.Response.StatusCode = exception is HttpException ? ((HttpException)exception).GetHttpCode() : 500;
httpContext.Response.TrySkipIisCustomErrors = true;
routeData.Values["controller"] = "Error";
routeData.Values["action"] = action;
controller.ViewData.Model = new HandleErrorInfo(exception, currentController, currentAction);
((IController)controller).Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData));
}
}
請注意,上面使用NLog記錄錯誤細節,但可能易於只需改變以支持別的東西。 另外,這個方法在解析ErrorController時會考慮你的IoC容器。
customError失去對錯誤的所有引用。 – 2013-05-01 04:09:55
可能的重複[如何處理ASP.NET MVC 3應用程序中未捕獲的異常?](http://stackoverflow.com/questions/6596648/how-do-i-handle-uncaught-exceptions-in-an- asp-net-mvc-3-application) – 2013-05-01 04:11:35
雖然customError重定向,但它正在創建一個新的http請求,因此丟失了所有以前的響應數據。你需要的是將redirectMode設置爲ResponseRewrite,這樣你就不會發出新的請求。 – 2013-05-01 04:12:59