全局过滤器中排除指定Controller和action方法(二)

本文介绍了如何在ASP.NET中使用特性标签来排除特定控制器和action方法从全局过滤器中,提供了一种更简便的方法,尽管需要为每个要排除的过滤器添加对应的标签。

   前文贴出了一种方式来排除Controller和action方法,但是感觉不太实用,因为如果遇到多个控制器,多个方法,就很难辨别了,今天我来介绍一种方式,加上标签,这种方法比较简单,相信你也会喜欢,麻烦的就是每个全局过滤器都要对应一个 不启用该全局过滤器的标签,不过为了功能实现,这点我们也暂时不去计较了吧。

首先,我们创建一个特性,内部什么都不用写,只是当作一个标识,占位的标识:

 1   /// <summary>
 2     /// 不启用压缩特性
 3     /// </summary>
 4     [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
 5     public class NoCompress : Attribute
 6     {
 7         public NoCompress()
 8         {
 9         }
10     }

接着呢,在全局过滤器中把你要排除的控制器或者过滤器一一贴上此标签。

 1         [NoCompress]
 2         public ActionResult Contact()
 3         {
 4             ViewBag.Message = "你的联系方式页。";
 5 
 6             return this.View();
 7         }
 8 
 9         [NoCompress]
10         public ActionResult Grid()
11         {
12             return this.View();
13         }

类似如此....

最后,就是写过滤器了,以压缩过滤器为例:

   /// <summary>
        /// 执行压缩方法
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            object[] actionFilter = filterContext.ActionDescriptor.GetCustomAttributes(typeof(NoCompress), false);
            object[] controllerFilter = filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(NoCompress), false);
            if (controllerFilter.Length == 1 || actionFilter.Length == 1)
            {
                return;
            }

            HttpRequestBase request = filterContext.HttpContext.Request;
            HttpResponseBase response = filterContext.HttpContext.Response;
            string acceptEncoding = request.Headers["Accept-Encoding"].ToLower();

            if (string.IsNullOrEmpty(acceptEncoding))
            {
                return;
            }

            if (acceptEncoding.Contains("gzip"))
            {
                response.Filter = new GZipStream(response.Filter, compress);
                response.AppendHeader("Content-Encoding", "gzip");
            }
            else if (acceptEncoding.Contains("deflate"))
            {
                response.Filter = new DeflateStream(response.Filter, compress);
                response.AppendHeader("Content-Encoding", "deflate");
            }
        }

接着上文一样,添加全局过滤器。

  public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
          filters.Add(new CompressFilterAttribute());
        }

好了,大功告成。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值