首页 > 解决方案 > 在 .Net Core Angular 5 网站中缓存破坏 index.html

问题描述

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

该项目使用 Angular cli 构建/打包并将哈希应用于捆绑的 js 和 css 文件:

在此处输入图像描述

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

当我按 F5 重新加载网站时,home从网站请求 index.html(如下)(在这种情况下为 304,因为它没有更改,如果有,它将获得最新的):

在此处输入图像描述

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

在此处输入图像描述

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

标签: angular.net-coreangular-clibrowser-cache

解决方案


这是我结合一堆答案后得出的结论。我的目标是永远不缓存 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");
        }
      }
    };
  });
}

其他 StackOverflow 答案:禁用 .Net Core 中的缓存| 缓存一年


推荐阅读