Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core: Disable browser cache

I'm a newbie web developer, and ASP.NET Core is the first web framework I've worked with. I noticed that my site wasn't updating when I hit F5, and I tracked it down to the browser cache being enabled. If I open Chrome DevTools > Network and select 'Disable brower cache', my site gets updated properly.

However, I don't want to go through this process every time I start debugging. Is there a way to disable caching programmatically in my ASP.NET Core app, e.g. through the Startup.cs file, so that this will automatically be done for me?

edit: I am using UseFileServer instead of UseStaticFiles. (I am not sure what either does, but UseFileServer works correctly for debugging while UseStaticFiles does not.) I tried passing a FileServerOptions argument to UseFileServer, but that doesn't let you configure the cache expiry like StaticFilesOptions does.

If it's relevant, I'm building a Web API project.

like image 771
James Ko Avatar asked Oct 16 '22 23:10

James Ko


1 Answers

You can still use StaticFileOptions when using 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);
like image 82
Pace Avatar answered Nov 15 '22 05:11

Pace