简体   繁体   English

.net 核心中的 GZIP 不起作用

[英]GZIP in .net core not working

I'm attempting to add Gzip middleware to my ASP.net core app.我正在尝试将 Gzip 中间件添加到我的 ASP.net 核心应用程序中。

I have added the following package :我添加了以下包:

"Microsoft.AspNetCore.ResponseCompression": "1.0.0" "Microsoft.AspNetCore.ResponseCompression": "1.0.0"

In my startup.cs for the Configure Services method I have the following :在我的配置服务方法的 startup.cs 中,我有以下内容:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<GzipCompressionProviderOptions>(options => options.Level = CompressionLevel.Fastest);
    services.AddResponseCompression(options =>
    {
        options.Providers.Add<GzipCompressionProvider>();
    });

    services.AddMvc();
}

In my Configure method I have the following :在我的配置方法中,我有以下内容:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseResponseCompression();
    app.UseMvc();
}

However when I try and load a page, it doesn't come through as Gzip compressed.但是,当我尝试加载页面时,它不会以 Gzip 压缩格式出现。 I have used both a string response and outputting a view.我使用了字符串响应和输出视图。 The response headers in chrome look like : chrome 中的响应标头如下所示:

在此处输入图片说明

I am on a windows machine developing in visual studio.我在 Visual Studio 中开发的 Windows 机器上。 When running the app I have tried just running from Visual Studio (Via F5), and also using the "dotnet run" command from command line.运行应用程序时,我尝试从 Visual Studio(通过 F5)运行,并从命令行使用“dotnet run”命令。 Neither output GZip compression.既不输出 GZip 压缩。

To Enable GZIP in .net core 2.*在 .net core 2.* 中启用 GZIP
1. Install Microsoft.AspNetCore.ResponseCompression with Install-Package Microsoft.AspNetCore.ResponseCompression command or nuget package manager. 1.使用Install-Package Microsoft.AspNetCore.ResponseCompression命令或 nuget 包管理器安装Microsoft.AspNetCore.ResponseCompression
2. Add the following code into Startup.cs 2.Startup.cs加入以下代码

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{

  app.UseResponseCompression();
  app.UseMvc();

}

public void ConfigureServices(IServiceCollection services)
{

  // Configure Compression level
  services.Configure<GzipCompressionProviderOptions>(options => options.Level = CompressionLevel.Fastest);

  // Add Response compression services
  services.AddResponseCompression(options =>
  {
      options.Providers.Add<GzipCompressionProvider>();
      options.EnableForHttps = true;
  });

}

Got this issue resolved by adding response compression option property "EnableForHttps" as shown below:通过添加响应压缩选项属性“EnableForHttps”解决了这个问题,如下所示:

services.AddResponseCompression(opt =>
        {
            opt.Providers.Add<GzipCompressionProvider>();
            opt.EnableForHttps = true;
        });
 services.Configure<GzipCompressionProviderOptions>(options => options.Level = 
 CompressionLevel.Fastest);

The answear from Mohammad Dayyan works great for compressing the HTML body. Mohammad Dayyan 的 answear非常适合压缩 HTML 正文。 If you want to compress also static client files like CSS or JS, the Startup.Configure method must look like this:如果您还想压缩 CSS 或 JS 等静态客户端文件,则Startup.Configure方法必须如下所示:

app.UseResponseCompression();
app.UseStaticFiles();

It's important to place app.UseResponseCompression() before app.UseStaticFiles() .这是一个放置重要app.UseResponseCompression()之前app.UseStaticFiles() Otherwise the static file handler sends the ressource to the client without applying any compression.否则,静态文件处理程序将资源发送到客户端而不应用任何压缩。

You can also add a black/or whitelist for mime types to compress in AddResponseCompression :您还可以为要在AddResponseCompression压缩的 mime 类型添加黑/或白名单:

services.Configure<GzipCompressionProviderOptions>(options => options.Level = CompressionLevel.Fastest);
services.AddResponseCompression(options => {
    options.MimeTypes = new string[]{
        "text/html",
        "text/css",
        "application/javascript",
        "text/javascript"
        // ...
    };

    options.Providers.Add<GzipCompressionProvider>();
});

Excluding specific mime types is also possible due to the options.ExcludedMimeTypes property.由于options.ExcludedMimeTypes属性,也可以排除特定的 MIME 类型。

Yes, there are good arguments to keep such things seperated from the application server and use some reverse proxy for things like compression.是的,有很好的论据可以将这些东西与应用程序服务器分开,并使用一些反向代理来进行压缩之类的事情。 This also allows the usage of the more effective Brotli algorithm in ASP.NET Core 2.1 LTS, which is officially only avaliable for the new 2.2 release (except custom middlewares relying on third party libraries).这也允许在 ASP.NET Core 2.1 LTS 中使用更有效的 Brotli 算法,该算法正式仅适用于新的 2.2 版本(依赖第三方库的自定义中间件除外)。

This was also my first idea, but it seems that nginx 1.17.3 currently doesn't playing well with gzip and ASP.NET Core 2.1.这也是我的第一个想法,但 nginx 1.17.3 目前似乎不能很好地与 gzip 和 ASP.NET Core 2.1 配合使用。 After enabling gzip, I get randomly FormatException: Invalid ETag name exceptions.启用 gzip 后,我随机收到FormatException: Invalid ETag name异常。 So it seems a suiteable workaround for me to let .NET Core do this job.因此,让 .NET Core 完成这项工作对我来说似乎是一个合适的解决方法。

I managed to enable the Response Compression Middleware when using IIS Express by removing在使用 IIS Express 时,我设法通过删除来启用响应压缩中间件

<httpCompression ...> 
...
</httpCompression> 

in .vs\\config\\applicationhost.config在 .vs\\config\\applicationhost.config

Solved it by putting通过放置解决它

app.UseResponseCompression(); app.UseResponseCompression();

before

app.UseMvc(); app.UseMvc();

in Startup.Configure, ie:在 Startup.Configure 中,即:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        app.UseResponseCompression(); // <--
        app.UseHttpsRedirection();
        app.UseMvc(); // <--
    }

By placing the UseResponseCompression twice under each other I managed to make it work.通过将UseResponseCompression相互放置两次,我设法使其工作。 I have no idea how this made it work.我不知道这是如何使它工作的。 I am still looking for an accepted solution.我仍在寻找可接受的解决方案。

Here is my solution:这是我的解决方案:

  1. Make sure your Fiddler's "Decode" function is disabled.确保您的 Fiddler 的“解码”功能被禁用。 And you can see a yellow bar in the response.您可以在响应中看到一个黄色条。 Disable Decode禁用解码

  2. Or exit Fillder or other proxy app and have a try.或者退出 Fillder 或其他代理应用程序并尝试一下。

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

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