簡體   English   中英

緩存在.Net Core Angular 5網站中破壞index.html

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

我正在使用.Net core和angular 5創建一個網站。我使用最新的.Net核心角度模板創建了該項目(使用安裝了.Net core 2.1的dotnet new angular )。

這個項目使用angular cli來構建/打包並將哈希應用到捆綁的js和css文件中:

在此輸入圖像描述

然而,在將我的網站發布到azure app服務之后,我發現當我瀏覽網站時,我會看到舊版本,直到我用F5手動刷新(不需要Ctrl-F5)。 這似乎是因為雖然js / css文件不會被緩存,但是包含對這些文件的引用的index.html頁面將從緩存中提供。

當我按F5重新加載網站時,從網站請求index.html(下面的home )(在這種情況下為304,因為它沒有改變,如果有,它將獲得最新的):

在此輸入圖像描述

但是,當我最初加載頁面時(通過書簽或鍵入地址等),頁面將直接從緩存中提供:

在此輸入圖像描述

這是預期的行為嗎? 為什么第一次加載頁面與按F5不同? 我可以/我應該阻止這種緩存嗎?

這是我在結合一堆答案后最終得到的結果。 我的目標是永遠不要緩存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中的緩存 緩存一年

不是一個簡潔或完美的解決方案,但這似乎有效,可能會讓人們走上正軌:

在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添加到index.html head部分,以防止緩存該文件:

<meta http-equiv="Cache-control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM