Gzip 压缩中间件在 asp.net core 2.0 中不起作用

Mar*_*sky 2 c# asp.net asp.net-core

我无法让 Gzip 压缩中间件在 asp.net core 2.0(或 2.1)中工作。我使用“Blank”Web 应用程序模板创建了一个新项目,并在 Startup.cs 中有以下代码:

public void ConfigureServices(IServiceCollection services)
{
    services.AddResponseCompression();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseResponseCompression();

    app.Run(async (context) =>
        {
            context.Response.Headers.Add("Content-Type", "text/plain");
            await context.Response.WriteAsync("Hello World!");
        });
}
Run Code Online (Sandbox Code Playgroud)

我确认 Chrome 在请求中发送了“Accept-Encoding: gzip, deflate, br”。

接受编码

但是,服务器不会对响应进行 gzip 编码:

内容编码

我究竟做错了什么?

我找到了这个讨论,并从那里尝试了一切,但没有帮助。

Ant*_*onB 7

我遇到了类似的问题(Mac 上的 asp.net core)

解决方案是确保在静态文件服务之前调用响应压缩。

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseCookiePolicy();

        // ordering matters here
        app.UseResponseCompression();
        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
Run Code Online (Sandbox Code Playgroud)

正确订购后,我可以在编码br(Brotli 压缩)下的 chrome 中看到它:

在此处输入图片说明