【问题标题】:Enable HTTP compression with ASP.NET Web API使用 ASP.NET Web API 启用 HTTP 压缩
【发布时间】:2017-10-13 21:18:12
【问题描述】:

我们通过我们的 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 压缩。根据this MSDN documentation

在 IIS、Apache 或 Nginx 中使用基于服务器的响应压缩技术,其中中间件的性能可能与服务器模块的性能不匹配。无法使用时使用响应压缩中间件:

  • IIS 动态压缩模块

  • Apache mod_deflate 模块

  • NGINX 压缩解压

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

  • 红隼

所以我认为在我的实例中执行此操作的首选方法是使用 IIS 动态压缩模块。因此,我在我的 Web.config 中尝试了这个,作为测试,遵循this example:

<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,因此我认为它没有被压缩。我错过了什么?如何设置它以尽可能以最佳方式提供压缩服务?

我已验证我的客户端正在发送gzip, deflate, brAccept-Encoding 标头。

更新

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

更新 2

我意识到压缩在我们的 Azure 服务器上工作,但仍然不能在我的本地 IIS 上工作。

【问题讨论】:

  • 不是所有类型的通配符,您是否在配置中尝试过特定的 mime 类型?
  • @Jasen 是的,我有,不幸的是无济于事。

标签: c# asp.net iis asp.net-web-api http-compression


【解决方案1】:

我在一个空的 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(缩写)

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
...

【讨论】:

    【解决方案2】:

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

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

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

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

    具体来说:

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

    【讨论】:

      【解决方案3】:

      您的 Windows Server(我假设您在服务器 Os 上工作)最有可能缺少的是 Web Server IIS 性能功能的安装,其中可以安装两个子模块:Static Content ConpressionDynamic Content Compression

      要检查它们是否已安装运行服务器管理器,选择Add Roles and Features,选择您的实例,在屏幕Server Roles 展开树节点Web Server (IIS)Web ServerPerformance 并验证复选框是否指示Static Content ConpressionDynamic Content Compression 如果不检查它们,则安装它们并继续功能安装。然后在 IIS 管理器和网站设置中重复所有静态和动态压缩配置的设置步骤。它现在应该可以工作了。

      【讨论】:

      • 我的操作系统是 Windows 10 Home,所以我不确定在哪里可以找到服务器管理器?
      • 好的,它稍微改变了问题,使我的上述答案毫无用处。要检查您是否在 IIS 中安装了所需的功能,请转到控制面板 -> 程序和功能 -> 打开或关闭 Windows 功能 -> 找到 Internet 信息服务节点并展开它 -> 展开万维网服务节点 -> 展开性能功能节点 - 并验证是否选中了动态和静态内容压缩的复选框 -> 如果未选中它们并继续安装。
      猜你喜欢
      • 1970-01-01
      • 2012-05-12
      • 2014-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多