如何在ASP.NET Core中缓存静态文件?

编程入门 行业动态 更新时间:2024-10-26 05:31:21
本文介绍了如何在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中缓存静态文件?

本文发布于:2023-11-13 21:45:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1585401.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:缓存   静态   文件   如何在   Core

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!