Cache Static Files in MVC Core (Logo, image, js, css, etc)

 Author: Shengtao Zhou       Created: 1/9/2019 7:06:01 PM       Modified: 2/4/2019 8:44:58 AM   More...

Some static resource files (like your website logo) are accessed very often but never change. To improve the site performance, you may like to have these file cached. 

MVC Core has output cache feature for the controller, but you can't use it for the _Layout.cshtml page. 

The solution is in ConfigureServices method inside the Startup.cs page, add Cache-Control to enable caching. To make things better, you can do it in 3 steps:


1. Add client site caching period to appSettings.json (the value is by seconds)

"StaticFiles": {
    "Cache-Control": "600"
}


2. ConfigureServices method inside Startup.cs page. Add the following code

app.UseStaticFiles(new StaticFileOptions
{
     OnPrepareResponse = context =>
     {
          string cachePeriod = Configuration.GetValue("StaticFiles:Cache-Control");
          if (!string.IsNullOrWhiteSpace(cachePeriod)) {
               var headers = context.Context.Response.GetTypedHeaders();
               context.Context.Response.Headers.Append("Cache-Control", "public,max-age=" + cachePeriod);
          }
     }
});


3. You can further improve it by filtering context.File.Name, or file extension
, like exclude javascript files from caching

if (!context.File.Name.EndsWith(".js"))


Then you can test it using Fiddler. The first time you access a page, the logo image will be loaded. When the second time access a page, the logo image will not be loaded.


One thing you need to be careful when testing static-file cache. When you a browser opened by Visual Studio debugging, the caching may be disabled by Visual Studio. So if you launch a browser by Visual Studio, you need to open a new tab or a new browser to testing caching.


More...          Back to List          

(Please enter you comments between 100 to 2000 characters. Thanks for your contribution.) 

         Created:       Modified: 

Editing a comment

       (Please enter you comments between 100 to 2000 characters. Please login before edit comment.)