压缩响应无效

时间:2019-06-26 05:27:38

标签: c# asp.net gzip response http-compression

我想在我的Asp.Net网站上压缩回复。我写了这段代码:

public static void CompressPage(HttpRequest Request, HttpResponse Response)
{
    string acceptEncoding = Request.Headers["Accept-Encoding"];
    Stream prevUncompressedStream = Response.Filter;

    if (acceptEncoding.IsEmpty())
    {
        return;
    }

    acceptEncoding = acceptEncoding.ToLower();

    if (acceptEncoding.Contains("gzip"))
    {
        Response.Filter = new GZipStream(prevUncompressedStream, CompressionMode.Compress);
        Response.AppendHeader("Content-Encoding", "gzip");
    }
    else if (acceptEncoding.Contains("deflate"))
    {
        Response.Filter = new DeflateStream(prevUncompressedStream, CompressionMode.Compress);
            Response.AppendHeader("Content-Encoding", "deflate");
    }
}

并将其称为Page_Load事件:

protected void Page_Load(object sender, EventArgs e)
{
    ...
    ZipHtmlPage.CompressPage(Request, Response);
}

问题是,当我在Page_Load中运行有无上述代码的代码时,响应的大小不会改变。

enter image description here

问题出在哪里?

谢谢


编辑1)

我认为"Content-Encoding", "gzip"不会添加到标题:

enter image description here

我不知道为什么?


编辑2)

当我使用HttpModule进行http压缩时:

public class CompressModule : IHttpModule
{
    public void Init(HttpApplication application)
    {
        application.BeginRequest += (new EventHandler(this.Application_BeginRequest));
    }

    private void Application_BeginRequest(Object source, EventArgs e)
    {
        HttpContext context = HttpContext.Current;
        context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
        HttpContext.Current.Response.AppendHeader("Content-Encoding", "gzip"); 
    }
    public void Dispose()
    {
    }
}

我在每页中都看到了这个

enter image description here

4 个答案:

答案 0 :(得分:1)

是否将以下代码添加到web.config文件中(用于CSS和javascript文件):

<system.webServer>
    <httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files">
      <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" staticCompressionLevel="9" />
      <dynamicTypes>
        <add mimeType="text/*" enabled="true" />
        <add mimeType="message/*" enabled="true" />
        <add mimeType="application/x-javascript" enabled="true" />
        <add mimeType="application/json" enabled="true" />
        <add mimeType="*/*" enabled="false" />
      </dynamicTypes>
      <staticTypes>
        <add mimeType="text/*" enabled="true" />
        <add mimeType="message/*" enabled="true" />
        <add mimeType="application/x-javascript" enabled="true" />
        <add mimeType="application/atom+xml" enabled="true" />
        <add mimeType="application/xaml+xml" enabled="true" />
        <add mimeType="*/*" enabled="false" />
      </staticTypes>
    </httpCompression>
...

也许此链接可以帮助您 How to implement GZip compression in ASP.NET?

答案 1 :(得分:1)

我认为添加压缩量是不标准的。我过去所做的工作是在启动文件中配置GZip。 我还注意到,压缩在调试模式下没有生效。 尝试以发布模式部署或运行​​您的应用,以查看它是否压缩了响应。

在启动配置服务的方法中,我有以下内容:

services.Configure<GzipCompressionProviderOptions>(options =>
{
    options.Level = CompressionLevel.Optimal;
});

答案 2 :(得分:1)

以下配置对我有用。只需使用下面的给定替换applicationHost.config中的httpCompression部分,然后重新启动IIS。就是这样!

  <httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files"
    staticCompressionDisableCpuUsage="95" staticCompressionEnableCpuUsage="60"
    dynamicCompressionDisableCpuUsage="95" dynamicCompressionEnableCpuUsage="50">
    <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" staticCompressionLevel="9" />
    <dynamicTypes>
      <add mimeType="text/*" enabled="true" />
      <add mimeType="message/*" enabled="true" />
      <add mimeType="application/x-javascript" enabled="true" />
      <add mimeType="*/*" enabled="false" />
      <add mimeType="application/json" enabled="true" />
      <add mimeType="application/json; charset=utf-8" enabled="true" />
    </dynamicTypes>
    <staticTypes>
      <add mimeType="text/*" enabled="true" />
      <add mimeType="message/*" enabled="true" />
      <add mimeType="application/x-javascript" enabled="true" />
      <add mimeType="application/atom+xml" enabled="true" />
      <add mimeType="application/xaml+xml" enabled="true" />
      <add mimeType="application/json" enabled="true" />
      <add mimeType="application/json; charset=utf-8" enabled="true" />
      <add mimeType="*/*" enabled="false" />
    </staticTypes>
  </httpCompression>

配置完此命令后,我得到以下标题,表明使用gzip压缩方法压缩了数据

Cache-Control → no-cache
Content-Encoding → gzip
Content-Length → 4202
Content-Type → application/json; charset=utf-8
Date → Wed, 22 Jul 2015 07:40:17 GMT
Expires → -1
Pragma → no-cache
Vary → Accept-Encoding
X-Powered-By → ASP.NET 

以上配置适用于整个IIS。如果您要为单个网站配置此文件,请替换

<section name="httpCompression" allowDefinition="AppHostOnly" overrideModeDefault="Deny" />

<section name="httpCompression" overrideModeDefault="Allow" />

在applicationHost.config中,而不是替换applicationHost.config中的httpCompression部分,而是将其添加到您网站的web.config中的system.webServer标记下

此外,请确保为数据指定了正确的MIME类型。就我而言,它是JSON,因此我使用了以下配置

<add mimeType="application/json" enabled="true" />
<add mimeType="application/json; charset=utf-8" enabled="true" />

对于您而言,我认为<add mimeType="text/*" enabled="true"/>就足够了。

注意:请确保已在系统上安装Dynamic Compression。在IIS下添加/删除功能。

编辑1:您也可以在代码中执行此操作,但不适用于js文件。如下所示,您可以创建一个属性并使用它来装饰控制器。我将创建一个基本控制器,每个控制器都将继承该基本控制器,并使用此属性对其进行修饰。

public class EnableCompressionAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {    
        var encodingsAccepted = filterContext.HttpContext.Request.Headers["Accept-Encoding"];
        if (string.IsNullOrEmpty(encodingsAccepted)) return;

        encodingsAccepted = encodingsAccepted.ToLowerInvariant();

        var response = filterContext.HttpContext.Response;    
        if(response == null) return;

        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);
        }
    }
}

答案 3 :(得分:0)

这不是压缩这样的页面的正确方法,首先,您需要检查浏览器是否接受gzipdeflate,然后开始压缩它,这就是为什么看到有线字符的原因。 / p>

private void Application_BeginRequest(Object source, EventArgs e)
{
    // wrong and dangerous
    HttpContext context = HttpContext.Current;
    context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
    HttpContext.Current.Response.AppendHeader("Content-Encoding", "gzip"); 
}

更好的方法:

void context_BeginRequest(object sender, EventArgs e)
{
    var app = (HttpApplication)sender;
    var encodings = app.Request.Headers.Get("Accept-Encoding");


    if (encodings == null)
        return;

    var baseStream = app.Response.Filter;


    // check if browser accepts gzip or deflate
    if (encodings.ToLower().Contains("gzip"))
    {
        app.Response.Filter = new GZipStream(baseStream, CompressionMode.Compress);
        app.Response.AppendHeader("Content-Encoding", "gzip");
        app.Context.Trace.Warn("GZIP compression on");
    }
    else if (encodings.ToLower().Contains("deflate"))
    {
        app.Response.Filter = new DeflateStream(baseStream, CompressionMode.Compress);
        app.Response.AppendHeader("Content-Encoding", "deflate");
        app.Context.Trace.Warn("Deflate compression on");
    }
}

我建议使用名为HttpCompress的库,您可以访问here。就像别人说的那样,为什么不使用内置的IIS压缩模块?