How to cache static files in ASP.NET Core? How to cache static files in ASP.NET Core? vue.js vue.js

How to cache static files in ASP.NET Core?


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 filesapp.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


This is working in ASP.NET Core 2.2 to 3.1:

I know this is a bit similar to Fredrik's answer but you don't have to type literal strings in order to get the cache control header

app.UseStaticFiles(new StaticFileOptions(){    HttpsCompression = Microsoft.AspNetCore.Http.Features.HttpsCompressionMode.Compress,                   OnPrepareResponse = (context) =>    {        var headers = context.Context.Response.GetTypedHeaders();        headers.CacheControl = new Microsoft.Net.Http.Headers.CacheControlHeaderValue        {            Public = true,            MaxAge = TimeSpan.FromDays(30)        };    }});