首页 文章

ASP.NET Core 1.0自定义压缩中间件和静态文件问题

提问于
浏览
0

我的初创公司的中间件配置看起来像这样:

public void Configure(IApplicationBuilder app)
{
    app.UseCompression();
    app.UseIISPlatformHandler();
    app.UseApplicationInsightsRequestTelemetry();
    app.UseCors("CorsPolicy");
    app.UseStaticFiles();
    app.UseMvc();
    app.UseApplicationInsightsExceptionTelemetry();
}

由于添加了 app.UseCompression() 中间件, wwwroot 中的静态html文件不再正确加载 . They don't resolve and tend to load indefinitely.

压缩中间件如下所示,源自here

public class CompressionMiddleware
{
    private readonly RequestDelegate nextDelegate;

    public CompressionMiddleware(RequestDelegate next)
    {
        nextDelegate = next;
    }

    public async Task Invoke(HttpContext httpContext)
    {
        var acceptEncoding = httpContext.Request.Headers["Accept-Encoding"];
        //Checking that we have been given the correct header before moving forward
        if (!(String.IsNullOrEmpty(acceptEncoding)))
        {
            //Checking that it is gzip
            if (acceptEncoding.ToString().IndexOf("gzip", StringComparison.CurrentCultureIgnoreCase) >= 0)
            {
                using (var memoryStream = new MemoryStream())
                {
                    var stream = httpContext.Response.Body;
                    httpContext.Response.Body = memoryStream;
                    await nextDelegate(httpContext);
                    using (var compressedStream = new GZipStream(stream, CompressionLevel.Optimal))
                    {
                        httpContext.Response.Headers.Add("Content-Encoding", new string[] { "gzip" });
                        memoryStream.Seek(0, SeekOrigin.Begin);
                        await memoryStream.CopyToAsync(compressedStream);
                    }
                }
            }
            else
            {
                await nextDelegate(httpContext);
            }
        }
        //If we have are given to Accept Encoding header or it is blank
        else
        {
            await nextDelegate(httpContext);
        }

    }
}

有谁知道为什么会发生这种情况?

注意:我使用的是DNX 1.0.0-rc1-update11.0.0-rc1-final 库 .

2 回答

  • 1

    我刚刚在/ wwwroot文件夹中的web.config中启用了压缩(就像我们在IIs applicationHost.config中所做的那样),并且它可以工作 . 无需添加压缩中间件 .

    http://www.brandonmartinez.com/2015/08/20/enable-gzip-compression-for-azure-web-apps/

  • 1

    web.config中定义的压缩仅适用于IIS而非自托管Web服务器 .

    我测试了 CompressionMiddleware 示例,您看到的问题是由 Content-Length 标头引起的 .

    如果已经设置了 Content-Length ,则浏览器会感到困惑,因为内容被压缩后,响应的实际大小与标头中定义的值不匹配 .

    删除内容长度标头解决了问题:

    httpContext.Response.Headers.Remove("Content-Length");    
    httpContext.Response.Headers.Add("Content-Encoding", new string[] { "gzip" });
    

    ...甚至可以在压缩内容时尝试指定实际的内容长度 .

相关问题