使用 OutputCacheAttribute 在 .Net 8 ASP.NET Web API 中创建缓存响应的选择退出

问题描述 投票:0回答:1

在实现最新版本的 .Net 响应缓存中间件时,我们需要制定一项策略,允许调用者在发送特定标头密钥时绕过缓存的响应。

为了简单起见,

"bypass-cache" = "true"
的键值足以作为示例。

// Program.cs

  // ...contents omitted from brevity.

  builder.Services.AddOutputCache(o =>
  {
    // Allow callers to bypass the cache with a specific header value.
    o.AddBasePolicy(o => 
      o.With(r => r.HttpContext.Request.Headers["bypass-cache"] == "true")
      .NoCache()
    );
  });

  // ...contents omitted from brevity.

  // I have experimented with moving this up and down to see if the order of middleware impacted it.
  app.UseOutputCache(); 

  // ...contents omitted from brevity.

控制器饰有

OutputCacheAttribute

  [HttpGet]
  [OutputCache]
  public async Task<IActionResult> ReadById(int id)
  {
    // Even when the value of this `check` is true, the policy is ignored 😠!
    var check = HttpContext.Request.Headers["bypass-cache"] == "true";

    var request = new ReadCrudByIdRequest(id);
    var result = await _mediator.Send(request);
    return Ok(result);
  }

邮差正在使用手动此端点。正如评论中提到的,我可以在控制器中看到值何时为 true 或 false,但它对策略没有任何影响。我还尝试创建一个明确命名的策略并用

[OutputCache(PolicyName = "bypass-cache")]
标记端点,但结果是相同的。

非常感谢任何帮助,谢谢!

asp.net-core caching .net-7.0 outputcache
1个回答
0
投票

您应该像下面这样实现此功能。

builder.Services.AddOutputCache(o =>
{
    o.AddBasePolicy(builder => builder.NoCache());

    o.AddPolicy("cache", o =>
        o.With(r => r.HttpContext.Request.Headers["cache"] == "true")
            .Expire(TimeSpan.FromMinutes(1))
        );
});

并使用它。

[HttpGet("test")]
[OutputCache(PolicyName = "cache")]
public async Task<IActionResult> ReadById(int id)
{
        
    return Ok(id);
}
© www.soinside.com 2019 - 2024. All rights reserved.