在ASP.NET MVC 3中压缩内容文件

5
我使用以下属性来修饰我的BaseController类。
public class OutputCompressAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        string encodingsAccepted = filterContext.HttpContext.Request.Headers["Accept-Encoding"];
        if (string.IsNullOrEmpty(encodingsAccepted))
            return;

        encodingsAccepted = encodingsAccepted.ToLowerInvariant();
        HttpResponseBase response = filterContext.HttpContext.Response;

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

问题在于,尽管此方法对视图和每个操作结果都有效,但该属性不适用于项目中/Content文件夹中的内容。我想知道如何使Content文件夹中的文件使用控制器,或者通过某种方式绑定或连接到允许我将这些过滤器附加到响应头的东西。
1个回答

9

不需要编写这样的Action Filters,也不需要重新发明轮子,您可以在IIS中激活压缩功能。您可以为静态和动态内容都开启该功能。


但是你不能在web.config中设置这个,对吧?在共享托管环境中如何设置压缩? - frennky
4
在这种情况下,你应该使用自定义的HTTP模块(IHttpModule),而不是使用操作筛选器(action filter)。操作筛选器(如其名称所示)是用于处理操作的。如果您想手动压缩静态文件,请使用模块。但是为了使此模块在静态资源(例如图像和JavaScript)中被调用,您需要配置应用程序以在集成管道模式下运行。 - Darin Dimitrov
@Darin,有使用HTTP模块压缩响应的示例吗? - bevacqua
当然,有很多例子。这是其中之一:http://forums.iis.net/p/1163687/1942354.aspx - Darin Dimitrov
@frennky 为什么你不能在 web.config 中设置这个呢?http://am-blog.no-ip.org/BlogEngine/post/2010/11/23/Enable-Gzip-compression-in-ASPNET-using-webconfig-configuration.aspx - angularrocks.com

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接