.NET 7 OutputCache 不使用命名策略

huangapple go评论61阅读模式
英文:

.NET 7 OutputCache Not Using Named Policies

问题

我正在尝试理解 OutputCaching,但遇到了一些问题:

  • 缓存确实起作用,但应用于所有控制器端点,即使它们没有该属性。我认为这可能是由于 AddBasePolicy() 导致的,但我更困惑的是我的下一个问题。
  • 我的命名策略似乎无法在 GetElementCached 方法上识别,始终应用 5 秒过期的基本策略。如果我删除基本策略,缓存根本不起作用。

我已经按照以下方式注册了服务和中间件:

.AddOutputCache(options =>
{
    options.AddBasePolicy(builder =>
        builder.Expire(TimeSpan.FromSeconds(5)));

    options.AddPolicy("DemoCache", builder =>
        builder.Expire(TimeSpan.FromSeconds(20)));
})

然后,我创建了两个返回测试数据的控制器方法:

[HttpGet("{index}/get-element-cache")]
[OutputCache(PolicyName = "DemoCache")]
[ProducesResponseType(typeof(string), StatusCodes.Status200OK)]
public async Task<IActionResult> GetElementCached(int index)
{
    return Ok(_myDb[index]);
}

[HttpGet("{index}/get-element-no-cache")]
[ProducesResponseType(typeof(string), StatusCodes.Status200OK)]
public async Task<IActionResult> GetElementNoCache(int index)
{
    return Ok(_myDb[index]);
}

我已经检查了示例和文档,并且对于为什么我的策略不起作用感到困惑,特别是基本策略有效,可以更改,使我相信我已正确配置它。

英文:

I am trying to understand OutputCaching but I am running into some problems:

  • Caching does work, but it's applying to all controller endpoints even if they don't have the attribute. I think this might be due to AddBasePolicy() but I'm more confused about my next point
  • My named policy does not seem to be recognised on the GetElementCached method, the base policy of 5 second expiry always applies. If I remove the base policy caching does not work at all

I have registered the service and subsequently middleware as follows:

                .AddOutputCache(options =&gt;
                {
                    options.AddBasePolicy(builder =&gt;
                        builder.Expire(TimeSpan.FromSeconds(5)));

                    options.AddPolicy(&quot;DemoCache&quot;, builder =&gt;
                        builder.Expire(TimeSpan.FromSeconds(20)));
                })

I have then created two controllers returning test data:

        [HttpGet(&quot;{index}/get-element-cache&quot;)]
        [OutputCache(PolicyName = &quot;DemoCache&quot;)]
        [ProducesResponseType(typeof(string), StatusCodes.Status200OK)]
        public async Task&lt;IActionResult&gt; GetElementCached(int index)
        {
            return Ok(_myDb[index]);
        }

        [HttpGet(&quot;{index}/get-element-no-cache&quot;)]
        [ProducesResponseType(typeof(string), StatusCodes.Status200OK)]
        public async Task&lt;IActionResult&gt; GetElementNoCache(int index)
        {
            return Ok(_myDb[index]);
        }

I've checked worked examples and the documentation and I'm confused why my policy won't apply especially given the base policy works and can be changed making me believe I've configured it correctly.

答案1

得分: 0

  1. 创建策略时,在调用 AddOutputCache 时指定缓存配置,即使它们没有该属性。

  2. 对于多个端点,创建策略以在调用 AddOutputCache 时指定缓存配置。基本策略为一组端点提供默认的缓存配置。您可以阅读配置多个端点或页面了解更多信息。

  3. 我的命名策略似乎在 GetElementCached 方法上没有被识别。

  4. 我们使用默认模板创建了一个 ASP.NET Core Web API 项目,然后在添加基本缓存之前,让我们运行我们的应用程序并访问默认的 Weather Forecast。我们注意到每次刷新时,我们都会得到不同的结果。这是因为默认代码会随机生成结果。

  5. 然后对 Program.cs 进行两个小更改:将输出缓存中间件添加到服务集合和请求管道中,如下所示:

    builder.Services.AddOutputCache(options =>
     {
         options.AddBasePolicy(builder =>
             builder.Expire(TimeSpan.FromSeconds(5)));
    
         options.AddPolicy("DemoCache", builder =>
             builder.Expire(TimeSpan.FromSeconds(20)));
     });
    ...
    app.UseOutputCache();
    
  6. 然后测试 WeatherForecast 以查看结果:

    [HttpGet("{index}/get-element-cache")]
    [OutputCache(PolicyName = "DemoCache")]
    [ProducesResponseType(typeof(string), StatusCodes.Status200OK)]
    public IEnumerable<WeatherForecast> GetElementCached()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }
    
    [HttpGet("{index}/get-element-no-cache")]
    [ProducesResponseType(typeof(string), StatusCodes.Status200OK)]
    public IEnumerable<WeatherForecast> GetElementNoCache()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }
    
  7. 结果:在再次访问 URL 后,我们可以看到响应现在被缓存了 20 秒:

.NET 7 OutputCache 不使用命名策略

英文:

> applying to all controller endpoints even if they don't have the
> attribute

Create policies when calling AddOutputCache to specify caching configuration that applies to multiple endpoints. A base policy provides default caching configuration for a collection of endpoints.You can read Configure multiple endpoints or pages to know more.

> My named policy does not seem to be recognised on the GetElementCached
> method,

I create an ASP.NET Core Web API project using the default template, before we add the basic caching, let’s run our app and hit the default Weather Forecast . We notice that each time we refresh, we get a different result. This is due to the default code randomizing the results.

Then make two small changes to Program.cs: add the output caching middleware to the service collection and request pipeline respectively. :

builder.Services.AddOutputCache(options =&gt;
 {
     options.AddBasePolicy(builder =&gt;
         builder.Expire(TimeSpan.FromSeconds(5)));

     options.AddPolicy(&quot;DemoCache&quot;, builder =&gt;
         builder.Expire(TimeSpan.FromSeconds(20)));
 });
...
app.UseOutputCache();

Then test WeatherForecast to see the result,:

        [HttpGet(&quot;{index}/get-element-cache&quot;)]
        [OutputCache(PolicyName = &quot;DemoCache&quot;)]
        [ProducesResponseType(typeof(string), StatusCodes.Status200OK)]
        public IEnumerable&lt;WeatherForecast&gt; GetElementCached()
        {
            return Enumerable.Range(1, 5).Select(index =&gt; new WeatherForecast
            {
                Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }

        [HttpGet(&quot;{index}/get-element-no-cache&quot;)]
        [ProducesResponseType(typeof(string), StatusCodes.Status200OK)]
        public IEnumerable&lt;WeatherForecast&gt; GetElementNoCache()
        {
            return Enumerable.Range(1, 5).Select(index =&gt; new WeatherForecast
            {
                Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }

Result: after we hit the URL again, we can see that the response is being cached for 20 seconds now :

.NET 7 OutputCache 不使用命名策略

huangapple
  • 本文由 发表于 2023年7月20日 20:54:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76730128.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定