ASP.NET MVC - Response.Filter is null when using A

2019-02-16 22:55发布

I want to use G-ZIP on my website, I googled the following code:

public class CompressAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var acceptEncoding = filterContext.HttpContext.Request.Headers["Accept-Encoding"];
        if (!string.IsNullOrEmpty(acceptEncoding))
        {
            acceptEncoding = acceptEncoding.ToLower();
            var 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);
            }
        }
    }
}

It works fine when I set the attribute to a Controller or an Action.

[Compress]
public class PostController : Controller

I don't want to manully do this on every piece of code, so I registered this attribute in

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

But when I run the application, exception came on this line of code:

response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);

the response.Filter is null.

I want to know why this is happening and how to solve this. Thanks!

- Update:

I found that the exception happens only when the controller contains a child action, and it's being invoked.

1条回答
我想做一个坏孩纸
2楼-- · 2019-02-16 23:40

My solution was to filter all child action.

if (filterContext.IsChildAction) return;

Use this code on the top of your method.

public class CompressAttribute : ActionFilterAttribute
{    
   public override void OnActionExecuting(ActionExecutingContext filterContext)
   {
       if (filterContext.IsChildAction) return;

       ...
    }
}
查看更多
登录 后发表回答