You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core中如何为指定端点实现Gzip压缩

仅为.NET Core项目特定端点启用Gzip压缩

要将全局启用的Gzip压缩改为仅对特定端点生效,你可以通过以下两种常用方案实现:

方案一:基于请求路径匹配启用压缩

这种方式适合目标端点路径固定的场景,通过MapWhen中间件仅在匹配指定路径时启用压缩:

  1. 保留原有的服务注册代码(AddResponseCompression和Configure<GzipCompressionProviderOptions>部分不变)
  2. 将全局的app.UseResponseCompression();替换为以下代码:
// 仅匹配指定路径时启用压缩
app.MapWhen(context => 
    // 这里添加需要启用压缩的路径,可根据需求增加或修改
    context.Request.Path.StartsWithSegments("/api/large-data") || 
    context.Request.Path.StartsWithSegments("/reports/export"), 
    appBuilder => {
        appBuilder.UseResponseCompression();
    });

这样只有请求路径匹配上述规则的端点才会触发Gzip压缩,其他端点不受影响。

方案二:使用自定义特性标记端点

这种方式更灵活,适合分散的端点,通过自定义特性标记需要压缩的端点,再让压缩中间件识别该特性:

步骤1:创建自定义特性

在项目中添加一个特性类:

public class EnableCompressionAttribute : Attribute, IEndpointMetadata
{
}

步骤2:配置压缩服务的匹配规则

修改AddResponseCompression的配置,添加MatchEndpoint逻辑,仅对带有特性的端点启用压缩:

builder.Services.AddResponseCompression(options =>
{
    options.EnableForHttps = true;
    options.Providers.Add<GzipCompressionProvider>();
    // 仅处理带有EnableCompressionAttribute的端点
    options.MatchEndpoint = (context, endpoint) =>
        endpoint?.Metadata.GetMetadata<EnableCompressionAttribute>() != null;
});

builder.Services.Configure<GzipCompressionProviderOptions>(options =>
{
    options.Level = CompressionLevel.Optimal;
});

步骤3:在目标端点上标记特性

在控制器的特定端点上添加[EnableCompression]特性:

[ApiController]
[Route("api/[controller]")]
public class DataController : ControllerBase
{
    [HttpGet("large-dataset")]
    [EnableCompression] // 该端点启用Gzip压缩
    public IActionResult GetLargeDataset()
    {
        // 返回大体积响应数据
        return Ok(new { /* 数据内容 */ });
    }

    [HttpGet("basic-info")]
    public IActionResult GetBasicInfo()
    {
        // 该端点不启用压缩
        return Ok(new { Message = "Basic information" });
    }
}

步骤4:保留全局中间件注册

继续保留app.UseResponseCompression();,此时压缩中间件只会对带有特性标记的端点生效。


内容的提问来源于stack exchange,提问作者Dilakshan AT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 09:52:30