使用ASP.NET Web API启用HTTP压缩

14
我们通过 Asp .NET Web API 为网站提供文件服务:
public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var clientHostname = System.Configuration.ConfigurationManager.AppSettings["ClientHostname"];

        var staticFileOptions = new StaticFileOptions()
        {
            OnPrepareResponse = staticFileResponseContext =>
            {
                staticFileResponseContext.OwinContext.Response.Headers.Add("Cache-Control", new[] { "public", "max-age=0" });
            }
        };

        app.MapWhen(ctx => ctx.Request.Headers.Get("Host").Equals(clientHostname), app2 =>
        {
            app2.Use((context, next) =>
            {
                if (context.Request.Path.HasValue == false || context.Request.Path.ToString() == "/") // Serve index.html by default at root
                {
                    context.Request.Path = new PathString("/Client/index.html");
                }
                else // Serve file
                {
                    context.Request.Path = new PathString($"/Client{context.Request.Path}");
                }

                return next();
            });

            app2.UseStaticFiles(staticFileOptions);
        });
    }
}

我想启用 HTTP 压缩。根据这份 MSDN 文档所述:

在 IIS、Apache 或 Nginx 中使用基于服务器的响应压缩技术,其中中间件的性能可能无法与服务器模块相匹配。当您无法使用以下内容时,请使用 Response Compression 中间件:

  • IIS 动态压缩模块

  • Apache mod_deflate 模块

  • NGINX 压缩和解压模块

  • HTTP.sys 服务器(以前称为 WebListener)

  • Kestrel

因此,我认为在我的情况下首选的方法是使用 IIS 动态压缩模块。根据这个示例,作为测试,我尝试在我的 Web.config 文件中进行了如下配置:

<configuration>
  <system.webServer>
    <httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files">
      <dynamicTypes>
        <add mimeType="*/*" enabled="true" />
      </dynamicTypes>
      <staticTypes>
        <add mimeType="*/*" enabled="true" />
      </staticTypes>
    </httpCompression>
  </system.webServer>
</configuration>

然而,响应标头不包括Content-Encoding,因此我认为它没有被压缩。我错过了什么?如何以最佳方式设置以进行压缩服务?

我已验证我的客户端发送了一个 Accept-Encoding 头部,其中包括了 gzip, deflate, br

更新

我尝试在IIS中安装动态HTTP压缩,因为默认情况下未安装。在我看来,我正在尝试提供静态内容服务,但我认为值得一试。 我验证了IIS管理器中启用了静态和动态内容压缩,但是我重新运行后仍旧没有压缩。

更新2

我意识到压缩已经在我们的Azure服务器上运行,但在我的本地IIS上仍然无法使用。


1
你尝试过在配置中使用特定的 MIME 类型,而不是通配符来匹配所有类型吗? - Jasen
1
@Jasen 是的,我做过,但不幸的是没有任何效果。 - Scotty H
3个回答

2

我在一个空的4.7 .NET Web项目中尝试了您的启动程序,并且至少在index.html上获得了压缩。我安装了动态压缩,添加了几个Owin包,以及下面的web.config等来使其正常工作。使用IIS/10

packages.config

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="1.0.5" targetFramework="net47" />
  <package id="Microsoft.Net.Compilers" version="2.1.0" targetFramework="net47" developmentDependency="true" />
  <package id="Microsoft.Owin" version="3.1.0" targetFramework="net47" />
  <package id="Microsoft.Owin.FileSystems" version="3.1.0" targetFramework="net47" />
  <package id="Microsoft.Owin.Host.SystemWeb" version="3.1.0" targetFramework="net47" />
  <package id="Microsoft.Owin.StaticFiles" version="3.1.0" targetFramework="net47" />
  <package id="Owin" version="1.0" targetFramework="net47" />
</packages>

Web.config(在没有httpCompression的情况下为我工作)

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  https://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <appSettings>
    <add key="ClientHostname" value="localhost" />
    <add key="owin:appStartup" value="WebApplication22.App_Start.Startup" />
  </appSettings>
  <system.web>
    <compilation targetFramework="4.7" />
    <httpRuntime targetFramework="4.7" />
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.5.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.5.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
  <system.webServer>
    <httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files">
      <dynamicTypes>
        <add mimeType="*/*" enabled="true" />
      </dynamicTypes>
      <staticTypes>
        <add mimeType="*/*" enabled="true" />
      </staticTypes>
    </httpCompression>
  </system.webServer>
</configuration>

Startup.cs (abbreviated)

using Microsoft.Owin;
using Microsoft.Owin.StaticFiles;
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication22.App_Start
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var clientHostname = System.Configuration.ConfigurationManager.AppSettings["ClientHostname"];

            var staticFileOptions = new StaticFileOptions()
            {
                OnPrepareResponse = staticFileResponseContext =>
                {
                    staticFileResponseContext.OwinContext.Response.Headers.Add("Cache-Control", new[] { "public", "max-age=0" });
                }
            };
            ...
            }
    }
}

响应

HTTP/1.1 200 OK
Cache-Control: public,max-age=0
Content-Type: text/html
Content-Encoding: gzip
Last-Modified: Tue, 17 Oct 2017 22:03:20 GMT
ETag: "1d347b5453aa6fa"
Vary: Accept-Encoding
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET
Date: Wed, 18 Oct 2017 02:27:34 GMT
Content-Length: 588
...

1

我发现以下三个资源在配置IIS上的动态压缩对于ASP.Net WCF和Web API页面非常有用。我认为它也适用于.Net Core,但我还没有尝试过。前两个资源有点老,但原则仍然适用:

https://blog.arvixe.com/how-to-enable-gzip-on-iis7/

https://www.hanselman.com/blog/EnablingDynamicCompressionGzipDeflateForWCFDataFeedsODataAndOtherCustomServicesInIIS7.aspx

https://learn.microsoft.com/en-us/iis/configuration/system.webserver/httpcompression/

具体来说:

  • 是的,您需要在IIS中安装并启用动态HTTP压缩模块
  • 确保在IIS管理器中选中了动态压缩:[您的服务器]/压缩Enable Dynamic Compression
  • 仔细检查客户端请求头中的MIME类型是否已经在配置编辑器下的system.webServer/httpCompression/dynamicTypes/中添加,并且类型处理程序的Enabled属性设置为True
  • 按照上述链接和其他答案中概述的方式添加web.config条目

0

很可能你的Windows服务器(我假设你在服务器操作系统上工作)缺少Web服务器IIS性能功能的安装,其中有两个子模块可以安装:静态内容压缩动态内容压缩

要检查它们是否已安装,请运行Server Manager,选择添加角色和功能,选择您的实例,在屏幕服务器角色中展开树节点Web服务器(IIS)Web服务器性能并验证复选框是否指示已安装静态内容压缩动态内容压缩。如果没有,请勾选它们并继续进行功能安装。然后在IIS管理器和网站设置中重复所有静态和动态压缩配置的设置步骤。现在应该可以正常工作了。


{btsdaf} - Scotty H
1
{btsdaf} - Jacek Blaszczynski

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