【问题标题】:Response cache not working in asp.net core project响应缓存在 asp.net 核心项目中不起作用
【发布时间】:2019-05-25 06:32:00
【问题描述】:

我尝试在 asp.net 核心项目中实现响应缓存,但它不起作用。这是startup.cs

public void ConfigureServices(IServiceCollection services) 
{
  services.AddResponseCaching();
  services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env) 
{
    app.UseResponseCaching();

    if (env.IsDevelopment()) 
    {
      app.UseDeveloperExceptionPage();
    }

这是我的控制器。

[ResponseCache(Duration = 30)]
public IActionResult Index() 
{
  ViewBag.IsMobile = RequestExtensions.IsMobileBrowser(ContextAccessor.HttpContext.Request);
  return View();
}

但仍然缓存控制头id

cache-control →no-cache, no-store

我缺少的地方请帮忙。此响应缓存不起作用,我从 Microsoft 文档中获取指导​​。

【问题讨论】:

标签: asp.net-mvc caching asp.net-core


【解决方案1】:

请注意,要使缓存正常工作,必须满足许多要求:

该请求必须导致来自服务器的 200(OK)响应。

请求方法必须是 GET 或 HEAD。

终端中间件,例如静态文件中间件,不得处理 响应缓存中间件之前的响应。

授权标头不得存在。

Cache-Control 标头参数必须有效,并且响应必须 标记为公开而不标记为私有。

Pragma: no-cache header/value 必须不存在,如果 Cache-Control 标头不存在,因为 Cache-Control 标头 存在时覆盖 Pragma 标头。 Set-Cookie 标头必须 不在场。

Vary 头参数必须有效且不等于*。

Content-Length 标头值(如果已设置)必须与 响应正文。

...

查看此网站:aspnet-core-response-cache

还要注意,如果 Postman 发出请求,请禁用“不发送缓存标头”选项。

看到这个帖子(结束帖子的图片):ASP.Net Core 2.0 - ResponseCaching Middleware - Not Caching on Server

【讨论】:

  • 感谢这个 sanmolhec,不同的标题和邮递员提示真的帮助了我
【解决方案2】:

要在 dotnet core 中设置响应缓存,请按以下步骤操作:

  1. 在 Startup.cs 中找到 ConfigureServices 方法并添加以下行:

    services.AddResponseCaching();

  2. Ins Startup.cs 找到Configure 方法并添加以下行:

        app.UseResponseCaching();
    
        app.Use(async (context, next) =>
        {
            context.Response.GetTypedHeaders().CacheControl =
                new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
                {
                    Public = true,
                    MaxAge = TimeSpan.FromSeconds(10)
                };
            context.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.Vary] =
                new string[] { "Accept-Encoding" };
    
            await next();
        });
    
  3. [ResponseCache] 属性应用于需要缓存的操作:

    [ResponseCache(Duration = 300, VaryByQueryKeys = new string[] { "id" })]
    [HttpGet]
    public async Task<IActionResult> Index(int id)
    {
        return View();
    }
    

【讨论】:

    【解决方案3】:

    我试过this Microsoft document,缓存成功了。

    Cache-Control: public,max-age=30
    Date: Thu, 27 Dec 2018 07:50:16 GMT
    

    我认为您缺少 app.Use(async =&gt; ) 部分。

    【讨论】:

    • 添加后也没有显示任何缓存控件
    【解决方案4】:

    有几个步骤可以让 ResponseCaching 发挥作用:

    1. 需要在Startup.cs中正确调用AddResponseCaching()UseResponseCaching()
    2. 页面必须返回一个 Cache-Control 标头,例如Cache-Control: public,max-age=60(请注意,它必须包含 public 指令)。您可以通过[ResponseCache] 属性来执行此操作,手动将其添加到响应标头等中。
    3. 方法必须是GET或HEAD,状态码必须是200
    4. 授权请求标头必须存在
    5. 如果客户端在请求中发送了他们自己的缓存控制头,它必须是有效的 - 即如果客户端传递了Cache-Control: max-age=0(如果用户按 F5,Chrome/Firefox/etc 会这样做),那么响应将永远不会从缓存中提供服务,因为根据定义,缓存的任何内容都早于 0 秒
    6. 各种其他条件。我建议确保您可以看到来自 Microsoft.AspNetCore.ResponseCaching.ResponseCachingMiddleware 的调试级日志,这将输出它没有缓存请求的原因

    就我而言,我想忽略客户端请求的 Cache-Control 标头,因此我添加了 ResponseCachingPolicyProvider 的子类,如下所示:

        /// <summary>
        /// By default, <see cref="ResponseCachingPolicyProvider"/> will not return a cached response
        /// if the client sends up a Cache-Control header indicating the client wants a fresh
        /// response. This is according to HTTP spec but is not the behavior we want, so
        /// we will remove the client's specified Cache-Control header while evaluating whether
        /// or not we should return the cached response for this request.
        /// </summary>
        public class CustomResponseCachingPolicyProvider : ResponseCachingPolicyProvider
        {
            public override bool IsCachedEntryFresh(ResponseCachingContext context)
            {
                var reqCacheControl = context.HttpContext.Request.Headers[HeaderNames.CacheControl];
                context.HttpContext.Request.Headers.Remove(HeaderNames.CacheControl);
                var result = base.IsCachedEntryFresh(context);
                context.HttpContext.Request.Headers.Add(HeaderNames.CacheControl, reqCacheControl);
                return result;
            }
        }
    

    如果请求是从内存缓存提供的,它会在响应中添加一个Age 标头,您可以检查该标头以验证缓存是否按预期运行。

    【讨论】:

      猜你喜欢
      • 2020-11-01
      • 1970-01-01
      • 2022-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-18
      • 1970-01-01
      相关资源
      最近更新 更多