Egor4eg
Egor4eg

Reputation: 2708

MVC.net disable attribute for particular methods

I have an action filter attribute on my BaseController class:

<CompressFilter()> _
Public Class BaseController

So, this filter is applied to all methods in all controllers of my app. Is it possible to disable this filter for some particular methods?

Upvotes: 2

Views: 2012

Answers (3)

Mikael Eliasson
Mikael Eliasson

Reputation: 5227

If you have access to the code for the CompressFilter it is. You can add a second Attribute. For example NoCompressAttribute. In the OnActionExecuting method of the CompressFilter you would look at the ActionDescriptors and if the NoCompressAttribute is applied you would not do the compression.

EDIT: Here is the code

 public class CompressFilter : ActionFilterAttribute
    {
        public bool Compress { get; set; }
        public CompressFilter()
        {
            Compress = true;
        }

        public CompressFilter(bool compress)
        {
            Compress = compress;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var compressAttribs = filterContext.ActionDescriptor.GetCustomAttributes(typeof(CompressFilter), true);
            foreach (var item in compressAttribs)
            {
                if (!((CompressFilter)item).Compress)
                {
                    return;
                }
            }

            HttpRequestBase request = filterContext.HttpContext.Request;

            string acceptEncoding = request.Headers["Accept-Encoding"];

            if (string.IsNullOrEmpty(acceptEncoding)) return;

            acceptEncoding = acceptEncoding.ToUpperInvariant();

            HttpResponseBase response = filterContext.HttpContext.Response;

            if (acceptEncoding.Contains("GZIP"))
            {
                response.AppendHeader("Content-encoding", "gzip");
                response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
            }
            else if (acceptEncoding.Contains("DEFLATE"))
            {
                response.AppendHeader("Content-encoding", "deflate");
                response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
            }
        }
    }

And then on the action you don't want compression do:

[CompressFilter(false)]
public virtual ActionResult Index()
{
}

Hope that helps

Upvotes: 3

The Smallest
The Smallest

Reputation: 5773

You can apply FilterAttribute to methods explicitly, instead of applying to all controller. Remove attribute from class BaseController, and add it only to methods you need to compress.

Upvotes: -1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

No it isn't. When you apply an action attribute to a controller it applies to all actions. You might need to move the action you want to exclude to a different controller.

Upvotes: 1

Related Questions