轉載自:http://blog.csdn.net/wangyy130/article/details/44241957
一、filter簡介
在了解自定義特性前,先引入一個概念filter,它是MVC中自帶的一種功能,在我們項目中通常會遇到在Action執行前或結束時,去執行日志記錄或錯誤處理等功能,通常可使用AOP截取來實現,但是在MVC中提供了filter過濾,大大方便了開發人員。
MVC中的filter類型:
二、應用
聲明一個自定義特性,繼承自ActionFilterAttribute
具體代碼:
//[AttributeUsage (AttributeTargets.All ,AllowMultiple =true)]//allmultiple容許多個標簽同時起作用 public class MyActionfilter:ActionFilterAttribute { public string Name { set; get; } //action執行之前先執行此方法 public override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); HttpContext.Current.Response.Write("<br />OnOnActionExecuting:" + Name); } //action執行之后先執行此方法 public override void OnActionExecuted(ActionExecutedContext filterContext) { base.OnActionExecuted(filterContext); HttpContext.Current.Response.Write("<br />onActionExecuted:" + Name); } //actionresult執行之前執行此方法 public override void OnResultExecuting(ResultExecutingContext filterContext) { base.OnResultExecuting(filterContext); HttpContext.Current.Response.Write("<br />OnResultExecuting:" + Name); } //actionresult執行之后執行此方法 public override void OnResultExecuted(ResultExecutedContext filterContext) { base.OnResultExecuted(filterContext); HttpContext.Current.Response.Write("<br />OnResultExecuted:" + Name); } }
使用
[MyActionfilter(Name="IndexAction")] public ActionResult Index() { Response.Write("<p>action被執行完了</p>"); return Content("<br/>ok:視圖被渲染了!<br/>"); }
執行上述代碼結果:
三、filter優先級別
如上所述,controller中的只有Index方法中有自定義特性,如果想讓所有的Action在執行時,都進行過濾,那么我們可以在Controller上添加自定義filter特性標簽,這樣執行它的范圍就是整個Controller了
而如果我們想要在所有的Controller中的所有Action中均執行此方法呢?我們可以在App_Start中的filterConfig中對自定義的過濾器進行注冊
Filters.Add(newMyActionFilterAttribute(){Name="Global"});//全局過濾
那么這樣的話就產生了優先級問題,離自己最近的優先級別最高,方法級別>Controller級別>全局級別
那么如果我想讓所有級別的方法均生效,就是每個級別的特性方法都去執行一遍,那么又該怎樣呢?這里就用到了AttributeUsage這個類了
將 MyActionfilter 上面注掉的解開
//[AttributeUsage (AttributeTargets.All ,AllowMultiple =true)]//allmultiple容許多個標簽同時起作用
讓AllowMultiple這個屬性的值設為true,此時便會執行所有聲明的特性方法了。
總結:通過以上對filter的使用,應該對自定義特性有了一個初步的了解,同時在項目中UI中用到的自定義特性,通過反射來解析,同時在處理異常時,我們可以利用異常特性HandleErrorAttribute來對程序中出現的異常進行處理,微軟默認在全局過濾器中加上了處理異常過濾,但是我們也可以加上自己的異常過濾。再者,MVC中自帶的前端UI校驗用的其實也是特性的相關實現。更多關於特性的知識有待我們進一步探索。
另外用得多的Filter可能就是ExceptionFilter了 比如發生異常寫日志啊啥的
MVC會自己實現一個HandleErrorAttribute 並且在 FilterConfig.cs 設置為全局的,所以如果自己需要自定義一個ExceptionFilter可以繼承 HandleErrorAttribute 然后重寫其中的 OnException
[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]//allmultiple容許多個標簽同時起作用 public class MyExceptionFilter : HandleErrorAttribute { public override void OnException(ExceptionContext filterContext) { base.OnException(filterContext); HttpContext.Current.Response.Redirect("http://www.baidu.com"); //HttpContext.Current.Response.Write("<br />發生異常,可以寫日志了"); } }