Vue.js – How to cache static files in ASP.NET Core

asp.net-corecachingstatic-filesvue.js

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);
    }
  });
}

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

audit screenshot

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?

network tab screenshot

Best Answer

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));
    }
});

Beware that you also need a way to invalidate cache when you make changes to static files.

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