Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Kestrel和.NET核心中间件压缩HTTP响应_.net_Asp.net Core Mvc_Middleware_Kestrel Http Server - Fatal编程技术网

使用Kestrel和.NET核心中间件压缩HTTP响应

使用Kestrel和.NET核心中间件压缩HTTP响应,.net,asp.net-core-mvc,middleware,kestrel-http-server,.net,Asp.net Core Mvc,Middleware,Kestrel Http Server,我希望使用.NETCore和KestrelWeb服务器动态编码HTTP响应。以下代码不起作用,响应无法加载到浏览器中 var response = context.Response; if (encodingsAccepted.ToArray().Any(x => x.Contains("gzip"))) { // Set Gzip stream. context.Response.Head

我希望使用.NETCore和KestrelWeb服务器动态编码HTTP响应。以下代码不起作用,响应无法加载到浏览器中

        var response = context.Response;


        if (encodingsAccepted.ToArray().Any(x => x.Contains("gzip")))
        {
            // Set Gzip stream.
            context.Response.Headers.Add("Content-Encoding", "gzip");
            // Wrap response body in Gzip stream.
            var body = context.Response.Body;


            context.Response.Body = new GZipStream(body, CompressionMode.Compress);


        }

所有这些都必须在调用下一个中间件之前发生(例如,
\u next.Invoke
或您拥有的东西),然后在调用下一个中间件之后,您应该
等待context.Response.Body.FlushAsync()

有关响应压缩的详细说明可在此处找到:

快速总结
可通过两个步骤启用压缩:

  • 添加对Microsoft.AspNetCore.ResponseCompression
  • 包的引用
  • 在应用程序启动时启用压缩:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddResponseCompression();
    }
    
    public void Configure(IApplicationBuilder app)
    {
        app.UseResponseCompression();
    
        ...
    }
    

  • 就这样。现在,如果客户端接受压缩编码,响应将被压缩。

    请注意,如果您使用的是https,则需要使用
    AddResponseCompression
    调用中的
    EnableForHttps
    选项。裁判: