简体   繁体   English

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

[英]Enable HTTP compression with ASP.NET Web API

We serve files for a website from our Asp .NET Web API: 我们从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);
        });
    }
}

I want to enable HTTP compression. 我想启用HTTP压缩。 According to this MSDN documentation 根据这个MSDN文档

Use server-based response compression technologies in IIS, Apache, or Nginx where the performance of the middleware probably won't match that of the server modules. 在IIS,Apache或Nginx中使用基于服务器的响应压缩技术,其中中间件的性能可能与服务器模块的性能不匹配。 Use Response Compression Middleware when you're unable to use: 当您无法使用时使用响应压缩中间件:

  • IIS Dynamic Compression module IIS动态压缩模块

  • Apache mod_deflate module Apache mod_deflate模块

  • NGINX Compression and Decompression NGINX压缩和解压缩

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

  • Kestrel 红隼

So I think the first preferable way to do this in my instance is with IIS Dynamic Compression Module. 所以我认为在我的实例中第一个更好的方法是使用IIS动态压缩模块。 Accordingly, I tried this in my Web.config, as a test, following this example : 因此,我在我的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>

However, the response headers do not include Content-Encoding , so I don't believe it is being compressed. 但是,响应标头不包含Content-Encoding ,因此我不相信它正在被压缩。 What am I missing? 我错过了什么? How can I set this up to serve with compression in the best way possible? 如何以最佳方式将其设置为压缩服务?

I have verified that my client is sending an Accept-Encoding header of gzip, deflate, br . 我已经验证我的客户端正在发送gzip, deflate, brAccept-Encoding标头。

Update 更新

I tried installing Dynamic HTTP Compression in IIS as it is not installed by default. 我尝试在IIS中安装Dynamic HTTP Compression,因为默认情况下没有安装它。 It seems to me I am trying to serve content statically, but I thought this was worth a try. 在我看来,我试图静态地提供内容,但我认为这值得一试。 I verified that both static and dynamic content compression are enabled in IIS Manager. 我确认在IIS管理器中启用了静态和动态内容压缩。 However, I re-ran it but still no compression. 但是,我重新运行它但仍然没有压缩。

Update 2 更新2

I realized compression was working on our Azure servers but still not with my local IIS. 我意识到压缩工作在我们的Azure服务器上,但仍然不在我的本地IIS上。

I tried your startup in an empty 4.7 .NET web project, and I get compression, at least on index.html. 我在一个空的4.7 .NET Web项目中尝试了你的启动,我得到了压缩,至少在index.html上。 I installed dynamic compression, added several Owin Packages, web.config below etc to get it working. 我安装了动态压缩,添加了几个Owin包,下面的web.config等,以使其正常工作。 Using IIS/10 使用IIS / 10

packages.config 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 (worked for me without httpCompression) 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) 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" });
                }
            };
            ...
            }
    }
}

Response 响应

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

I have found these three resources to be useful in configuring dynamic compression for IIS on either ASP.Net WCF and Web API pages. 我发现这三个资源在ASP.Net WCF和Web API页面上为IIS配置动态压缩时非常有用。 I presume it also works for .Net Core but I haven't yet tried. 我认为它也适用于.Net Core,但我还没有尝试过。 The first two are a bit old but the principles still apply: 前两个有点旧但原则仍然适用:

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

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

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

Specifically: 特别:

  • Yes, you do need the Dynamic HTTP Compression module installed in IIS, and enabled 是的,您确实需要在IIS中安装动态HTTP压缩模块并启用
  • Ensure that Dynamic compression is checked in IIS Manager under [Your server]/ Compression : 确保在[您的服务器] /压缩下的IIS管理器中检查动态压缩: 启用动态压缩
  • Double-check that the MIME type in the client's request header is specifically added in the Configuration Editor under system.webServer/httpCompression/dynamicTypes/ , and that the type handler' Enabled property is set to True 仔细检查客户端请求标头中的MIME类型是否在system.webServer/httpCompression/dynamicTypes/下的配置编辑器中专门添加,并且类型处理程序' Enabled属性设置为True
  • Add the web.config entries as outlined in the links above and the other answer 添加web.config条目,如上面的链接和其他答案中所述

Most probably this what is missing on your Windows Server (I assume you work on server Os) is installation of Web Server IIS Performance features in which there are two submodules which can be installed: Static Content Conpression and Dynamic Content Compression . 最有可能的是,Windows Server上缺少的东西(我假设您在服务器Os上工作)是Web服务器IIS性能功能的安装,其中有两个子模块可以安装: Static Content ConpressionDynamic Content Compression

To check if they are installed run Server Manager, select Add Roles and Features , select your instance, in screen Server Roles expand tree nodes Web Server (IIS) , Web Server , Performance and verify if checkboxes indicate that Static Content Conpression and Dynamic Content Compression are installed if not check them and continue with feature installation. 要检查它们是否已安装,请运行服务器管理器,选择Add Roles and Features ,选择您的实例,在屏幕Server Roles展开树节点Web Server (IIS)Web ServerPerformance并验证是否复选框表示Static Content ConpressionDynamic Content Compression如果不检查则安装并继续功能安装。 Then repeat all setup steps for static and dynamic compression configuration in IIS Manager and in Web Site settings. 然后在IIS管理器和网站设置中重复静态和动态压缩配置的所有设置步骤。 It should work now. 它现在应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM