如何在ASP.NET Core中缓存静态文件? [英] How to cache static files in ASP.NET Core?

查看:261
本文介绍了如何在ASP.NET Core中缓存静态文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法在ASP.NET Core 2.2中启用静态文件的缓存。我的 Configure 中有以下内容:

I can't seem to enable caching of static files in ASP.NET Core 2.2. I have the following in my Configure:

public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
  if (env.IsDevelopment()) {
    app.UseDeveloperExceptionPage();
    app.UseCors(...);
  }
  else {
    app.UseHsts();
  }

  app.UseHttpsRedirection();
  app.UseAuthentication();
  app.UseSignalR(routes => { routes.MapHub<NotifyHub>("/..."); });

  app.UseResponseCompression();
  app.UseStaticFiles();
  app.UseSpaStaticFiles(new StaticFileOptions() {
    OnPrepareResponse = (ctx) => {
      ctx.Context.Response.Headers[HeaderNames.CacheControl] = "public, max-age=31557600"; // cache for 1 year
    }
  });
  app.UseMvc();

  app.UseSpa(spa => {
    spa.Options.SourcePath = "ClientApp";
    if (env.IsDevelopment()) {
      spa.UseVueCli(npmScript: "serve", port: 8080);
    }
  });
}

当我尝试使用chrome在HTTPS上审核生产站点时,我不断收到使用有效的缓存策略为静态资产提供服务:

When I try and Audit the production site on HTTPS using chrome I keep getting "Serve static assets with an efficient cache policy":

在网络选项卡中,标题中没有提及缓存,当我按F5键时,似乎所有内容都由磁盘缓存提供。但是,如果审核未显示,我如何确定我的缓存设置正常?

In the network tab there is no mention of caching in the headers, when I press F5 it seems everything is served from disk cache. But, how can I be sure my caching setting is working if the audit is showing its not?

推荐答案

我不知道 UseSpaStaticFiles 是什么,但是您可以在 UseStaticFiles 中添加缓存选项。您错过了设置 Expires 标头的操作。

I do not know what UseSpaStaticFiles is but you can add cache options in UseStaticFiles. You have missed to set an Expires header.

// Use static files
app.UseStaticFiles(new StaticFileOptions {
    OnPrepareResponse = ctx =>
    {
        // Cache static files for 30 days
        ctx.Context.Response.Headers.Append("Cache-Control", "public,max-age=2592000");
        ctx.Context.Response.Headers.Append("Expires", DateTime.UtcNow.AddDays(30).ToString("R", CultureInfo.InvariantCulture));
    }
});

请注意,对静态文件进行更改时,还需要一种使缓存无效的方法。

我写了一篇关于此的博客文章:缩小并缓存ASP.NET Core中的静态文件

I have written a blog post about this: Minify and cache static files in ASP.NET Core

这篇关于如何在ASP.NET Core中缓存静态文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆