dotnet core 2 asp .net 中的路由特定响应压缩?

Bar*_*all 6 .net-core asp.net-core

这可能看起来有点毫无意义,但我希望我的 API 端点之一支持“最佳”gzip 压缩。对于所有其他我想要“无”或“最快”。

这可能吗?我怎样才能实现这个目标?

最理想的是,我想以某种方式从控制器操作中向服务表明我希望对当前请求进行 GZipped 以及要使用的设置。

我想我可以尝试从 ResponseCompressionMiddleware 中提取 Invoke 方法并将其混入它自己的服务中,但我想先看看是否有更简单的方法。

Caj*_*ing 5

因此,评论提到使用 AspNetCore 的开箱即用支持Middleware作为特定于路由的 Filtervia运行MiddlewareFilterAttribute,但没有提供实际的实现...

这是一种优雅的方法,使用开箱即用的响应压缩中间件,只需几行代码即可使其工作。。。

在 Startup/Program.cs 中,您必须为开箱即用的响应压缩中间件依赖项设置 DI:

builder.Services.AddResponseCompression(options => options.EnableForHttps = true);
Run Code Online (Sandbox Code Playgroud)

然后添加一个新的属性来封装它,以便简化每个端点的注释代码,这样它就可以只在一个地方得到增强:

using Microsoft.AspNetCore.Mvc;

public class EnableRouteResponseCompressionAttribute : MiddlewareFilterAttribute
{
    public EnableRouteResponseCompressionAttribute () 
        : base(typeof(EnableRouteResponseCompressionAttribute ))
    { }

    public void Configure(IApplicationBuilder applicationBuilder) 
        => applicationBuilder.UseResponseCompression();
}

Run Code Online (Sandbox Code Playgroud)

现在您可以简单地使用它:

[Route("get-some-compressed-data")]
[HttpGet]
[EnableRouteResponseCompression] //<== The Magic is Here!
public async Task<Data> GetSomeCompressedData()
{
    // . . . get the data . . . 
}

Run Code Online (Sandbox Code Playgroud)