ASP.NET MVC- ActionFilter的使用

  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();
        }
相关文章
相关标签/搜索