ASP.NET Core:禁用浏览器缓存

Jam*_* Ko 5 c# asp.net caching visual-studio asp.net-core

我是一名 Web 开发新手,ASP.NET Core 是我使用过的第一个 Web 框架。我注意到当我点击 F5 时我的网站没有更新,我追踪到启用了浏览器缓存。如果我打开 Chrome DevTools > Network 并选择“禁用浏览器缓存”,我的网站会正确更新。

但是,我不想每次开始调试时都经历这个过程。有没有办法在我的 ASP.NET Core 应用程序中以编程方式禁用缓存,例如通过Startup.cs文件,以便自动为我完成?

编辑:我正在使用UseFileServer而不是UseStaticFiles. (我不确定两者都有什么作用,但UseFileServer在调试时可以正常工作,而UseStaticFiles不能正常工作。)我尝试将FileServerOptions参数传递给UseFileServer,但这并不能让您像StaticFilesOptions那样配置缓存到期时间。

如果相关,我正在构建一个 Web API 项目。

Pac*_*ace 5

StaticFileOptions使用时您仍然可以使用UseFileServer

var fsOptions = new FileServerOptions();
fsOptions.StaticFileOptions.OnPrepareResponse = (context) =>
{
    // Disable caching of all static files.
    context.Context.Response.Headers["Cache-Control"] = "no-cache, no-store";
    context.Context.Response.Headers["Pragma"] = "no-cache";
    context.Context.Response.Headers["Expires"] = "-1";
}
app.UseFileServer(fsOptions);
Run Code Online (Sandbox Code Playgroud)