ActionFilter是穿插在Action執行過程,在Action執行先後提供擴展的功能。ActionFilter用途很是的廣,用在頁面壓縮、緩存、錯誤處理,登錄驗證。緩存
ActionFilter的實現須要繼承自ActionFilterAttribute抽象類,而且覆蓋須要使用的方法。ide
ActionFilterAttribute類中有四個可重的方法,分別是OnActionExecuting,OnActionExecuted,OnResultExecuting,OnResultExecuted。spa
這四個方法的執行順序是 OnActionExecuting->OnActionExecuted->OnResultExecuting->OnResultExecutedcode
實現步驟blog
1.先創建一個Filter文件夾,在裏面新建一個類FilterDemo繼承
代碼以下:it
using System.Web.Mvc; namespace MvcApplication2.Filter { public class DemoFilter : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { HttpContext.Current.Response.Write("OnActionExecuting:正要準備執行Action的時候但還未執行時執行"); } public override void OnActionExecuted(ActionExecutedContext filterContext) { HttpContext.Current.Response.Write("OnActionExecuted:Action執行時但還未返回結果時執行"); } public override void OnResultExecuting(ResultExecutingContext filterContext) { HttpContext.Current.Response.Write("OnResultExecuting:OnResultExecuting也和OnActionExecuted同樣,但前者是在後者執行完後才執行"); } public override void OnResultExecuted(ResultExecutedContext filterContext) { HttpContext.Current.Response.Write("OnResultExecuted:是Action執行完後將要返回ActionResult的時候執行"); } } }
2.而後在Controller裏,加上[DemoFilter]標記,則在執行這個Action的時候會先進入FilterDemo類裏,執行裏面的方法io
[DemoFilter] public ActionResult FilterDemo() { return View(); }