定義異常捕獲類:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class ExceptionAttribute : FilterAttribute, IExceptionFilter
{
public virtual void OnException(ExceptionContext filterContext)
{
string message = string.Format("消息類型:{0}<br>消息內容:{1}<br>引發異常的方法:{2}<br>引發異常源:{3}"
, filterContext.Exception.GetType().Name
, filterContext.Exception.Message
, filterContext.Exception.TargetSite
, filterContext.Exception.Source + filterContext.Exception.StackTrace
);
//記錄日志
WriteLog.WriteInfo(message);
//拋出異常信息
filterContext.Controller.TempData["ExceptionAttributeMessages"] = message;
//轉向
filterContext.ExceptionHandled = true;
filterContext.Result = new RedirectResult(Globals.ApplicationDirectory + "/Error/ErrorDetail/");
}
}
Mvc全局使用異常捕獲類:
Global.asax.cs文件注冊全局異常捕獲類
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new Models.ExceptionAttribute());
filters.Add(new HandleErrorAttribute());
}
實現其他全局過濾的思想同上.
