ActionFilter的使用场景及示例

    ActionFilter里面有几个可以重写的事件:OnActionExecuting,OnActionExecuted,OnResultExecuting,OnResultExecuted 从字面我们大概就知道他们运行的顺序了。

    示例:看四个方法的执行次序。定义一个继承ActionFilterAttribute并重写其内部方法的类。

public class SimpleFilterAttribute:ActionFilterAttribute
    {
        public int ID { get; set; }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            File.AppendAllText(@"F:/actionlog.txt", this.ID +" "+ "OnActionExecuting <br>");
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            File.AppendAllText(@"F:/actionlog.txt", this.ID + " " + "OnActionExecuted  <br>");
        }

        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            File.AppendAllText(@"F:/actionlog.txt", this.ID + " " + "OnResultExecuting <br>");
        }

        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            File.AppendAllText(@"F:/actionlog.txt", this.ID + " " + "OnResultExecuted <br>");
        }
    }

 在HomeController的Action方法上面标志。

   [SimpleFilterAttribute(ID=1,Order=1)]
   public ActionResult Index()

执行后,查看actionlog.txt文件可以看到是按照:OnActionExecuting,OnActionExecuted,OnResultExecuting,OnResultExecuted 次序执行的。

    1.OnActionExecuting 
       在Action方法调用前使用,使用场景:如何验证登录等。

public class LoginFilterAttribute:ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //当用户没有验证时
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
               
                filterContext.Result = new RedirectToRouteResult("Default", 
                    new RouteValueDictionary(new {action="Login"})
                    );
            }
        }
    }

   [LoginFilterAttribute]
    public ActionResult Index()

    2.OnActionExecuted
    
  在Action方法调用后,result方法调用前执行,使用场景:异常处理

   

public class ErrorActionFilter:ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (filterContext.Exception != null)
            {
                filterContext.Canceled = true;
                filterContext.Result = new RedirectToRouteResult("Demo", new RouteValueDictionary(new { action = "ErrorPage" }));
            }
        }
    }

       [ErrorActionFilter]
        public void ErrorHandler()
        {
            throw new Exception();
           
        }

    3.OnResultExecuting
     在result执行前发生(在view 呈现前),使用场景:设置客户端缓存,服务器端压缩.

      明天写一下。

    4.OnResultExecuted
    在result执行后发生,使用场景:异常处理,页面尾部输出调试信息。

    明天写一下。

  

posted @ 2013-03-21 23:41  WIN8新人  阅读(320)  评论(0编辑  收藏  举报