HandleErrorAttribute源代码:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] public class HandleErrorAttribute : FilterAttribute, IExceptionFilter { private const string DefaultView = "Error"; private readonly object _typeId = new object(); private Type _exceptionType = typeof(Exception); private string _master; private string _view; public Type ExceptionType { get { return this._exceptionType; } set { if (value == null) { throw new ArgumentNullException("value"); } if (!typeof(Exception).IsAssignableFrom(value)) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, MvcResources.ExceptionViewAttribute_NonExceptionType, new object[] { value.FullName })); } this._exceptionType = value; } } public string Master { get { return this._master ?? string.Empty; } set { this._master = value; } } public override object TypeId { get { return this._typeId; } } public string View { get { if (string.IsNullOrEmpty(this._view)) { return "Error"; } return this._view; } set { this._view = value; } } public virtual void OnException(ExceptionContext filterContext) { if (filterContext == null) { throw new ArgumentNullException("filterContext"); } if (filterContext.IsChildAction) { return; } if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled) { return; } Exception exception = filterContext.Exception; if (new HttpException(null, exception).GetHttpCode() != 500)//注意这里 { return; } if (!this.ExceptionType.IsInstanceOfType(exception)) { return; } string controllerName = (string)filterContext.RouteData.Values["controller"]; string actionName = (string)filterContext.RouteData.Values["action"]; HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName); filterContext.Result = new ViewResult { ViewName = this.View, MasterName = this.Master, ViewData = new ViewDataDictionary<HandleErrorInfo>(model), TempData = filterContext.Controller.TempData }; filterContext.ExceptionHandled = true; filterContext.HttpContext.Response.Clear(); filterContext.HttpContext.Response.StatusCode = 500; filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; } }