.Net Core Angular 5 网站中的缓存破坏 index.html

Cache busting index.html in a .Net Core Angular 5 website

我正在使用 .Net 核心创建网站,angular 5. 我使用最新的 .Net 核心 angular 模板创建了项目(使用 dotnet new angular 和 .Net 核心 2.1安装)。

此项目使用 angular cli 到 build/package 并将散列应用于捆绑的 js 和 css 文件:

然而,在将我的网站发布到 Azure 应用程序服务后,我发现当我浏览该网站时,我会看到旧版本,直到我使用 F5 手动刷新(不需要 Ctrl-F5)。这似乎是因为虽然 js/css 文件不会被缓存,但包含对这些文件的引用的 index.html 页面将从缓存中提供。

当我按 F5 重新加载网站时,从网站请求 index.html(下面的 home)(在本例中为 304,因为它没有更改,如果有,它将得到最新):

然而,当我最初加载页面时(通过书签或输入地址等),页面直接从缓存中提供:

这是预期的行为吗?为什么第一次加载页面与按 F5 不同? I/should 我可以阻止这种缓存吗?

这不是一个巧妙或完美的解决方案,但这似乎奏效了,可能会让人们走上正轨:

在 Startup.cs 的 Configure() 中我添加了这个

app.Use(async (c, next) =>
{
    if (c.Request.Path == "/")
    {
        c.Response.Headers.Add("Cache-Control", "no-store,no-cache");
        c.Response.Headers.Add("Pragma", "no-cache");
    }
    await next();
});

自从添加这个后,我一直无法重现我的问题。

这是我综合了一堆答案后得出的结论。我的目标是永远不缓存 index.html。当我在那里时,由于 Angular 很好地缓存了 jscss 文件,我让它缓存了一年的所有其他资产。

只需确保您对在 Angular 之外管理的资产(例如图像)使用缓存清除机制。

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

  if (env.IsDevelopment())
  {
    // no caching
    app.UseSpaStaticFiles();
  }
  else
  {
    app.UseSpaStaticFiles(new StaticFileOptions
    {
      OnPrepareResponse = context =>
      {
        context.Context.Response.Headers.Add("Cache-Control", "max-age=31536000");
        context.Context.Response.Headers.Add("Expires", "31536000");
      }
    });
  }

  // ...

  app.UseSpa(spa =>
  {
    spa.Options.DefaultPageStaticFileOptions = new StaticFileOptions
    {
      OnPrepareResponse = context =>
      {
        // never cache index.html
        if (context.File.Name == "index.html")
        {
          context.Context.Response.Headers.Add("Cache-Control", "no-cache, no-store");
          context.Context.Response.Headers.Add("Expires", "-1");
        }
      }
    };
  });
}

其他 Whosebug 答案:Disable Caching in .Net Core | Cache for a year