【问题标题】:How to control browser cache expiration when serving SPA from wwwroot in ASP.NET Core App在 ASP.NET Core App 中从 wwwroot 提供 SPA 时如何控制浏览器缓存过期
【发布时间】:2020-01-16 11:38:02
【问题描述】:

我们从 ASP.NET Core 2.1 Web 后端的 wwwroot 文件夹提供基于 Angular 的 SPA 的生产包。 否则,此 ASP.NET Core Web 后端仅充当 SPA 的 REST API。

为此,我在 Startup.cs 中将这一行添加到 ConfigureServices 方法中:

 services.AddSpaStaticFiles(config => config.RootPath = "wwwroot");

这是配置方法

app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseSpaStaticFiles();

            app.UseMvc();
            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "wwwroot";
            });

这可行,但我注意到当我在 wwwroot 中更新捆绑包时,客户端并不总是选择新版本。通常他们必须在浏览器中强制刷新页面以获取最新版本。

AFAIK 这与浏览器缓存有关。

当我部署新版本的 SPA 捆绑包时,如何控制缓存的过期时间,以便客户端浏览器立即获取新版本?

【问题讨论】:

    标签: c# angular asp.net-core .net-core asp.net-core-mvc


    【解决方案1】:

    您可以使用此代码清除缓存

          app.UseSpaStaticFiles(new StaticFileOptions()
                {
                    OnPrepareResponse = ctx =>
                    {
                        var headers = ctx.Context.Response.GetTypedHeaders();
                        headers.CacheControl = new CacheControlHeaderValue
                        {
                            Public = true,
                            MaxAge = TimeSpan.FromDays(0)
                        };
    
                    }
                });
    
    
         app.UseSpa(spa =>
                {
                    spa.Options.SourcePath = "ClientApp";
                    spa.Options.DefaultPageStaticFileOptions = new StaticFileOptions()
                    {
                        OnPrepareResponse = ctx => {
                            var headers = ctx.Context.Response.GetTypedHeaders();
                            headers.CacheControl = new CacheControlHeaderValue
                            {
                                Public = true,
                                MaxAge = TimeSpan.FromDays(0)
                            };
                        }
                    };
    
                    if (env.IsDevelopment())
                    {
                        spa.UseAngularCliServer(npmScript: "start");
                    }
                });
    

    【讨论】:

    • 对我来说,这似乎完全禁用了缓存。我不明白这是如何回答问题的?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    • 1970-01-01
    • 2015-02-07
    • 2018-06-29
    • 2011-11-12
    • 2011-07-17
    • 2020-04-24
    相关资源
    最近更新 更多