Asp.net-core – How to cache css,js or images files to asp.net core

asp.net-coreasp.net-core-mvc

An intermittent proxy was causing my pages to get cached with an asp.net core site I deployed. The web server was not caching pages.

I added request and response caching to prevent any caching this proxy was causing

In my Startup.cs

        app.UseStaticFiles();

        app.UseIdentity();

        app.Use(async (context, next) =>
        {
            context.Response.Headers.Append("Cache-Control", "no-cache");
            context.Response.Headers.Append("Cache-Control", "private, no-store");
            context.Request.Headers.Append("Cache-Control", "no-cache");
            context.Request.Headers.Append("Cache-Control", "private, no-store");
            await next();
        });

I can see in fiddler these no cache headers have been added to my pages as well as to javascript files, css files and image files.

  1. How do I limit this no caching headers to only apply to asp.net mvc pages so these no cache headers don't showup in fiddler for non page files like js,css, and image files

  2. Is there a way that for HTTP requests for css and js files to not check if the file exists on the server for every request, and rather just the browser version is used for the first get of those files. The reason I ask is that on heavy load (1000 users) I in Fiddler I notice I get 404 errors for HTTPGETs for my css,js and image file so I'm trying to limit the number of requests for those resources. When the requests are successful(not under load) I get 304 responses (not modified). Is there not a way to tell the browser to not make the request in the first place and use the local cached version.

Best Answer

app.UseStaticFiles(new StaticFileOptions()
{
    OnPrepareResponse =
        r =>
        {
            string path = r.File.PhysicalPath;
            if (path.EndsWith(".css") || path.EndsWith(".js") || path.EndsWith(".gif") || path.EndsWith(".jpg") || path.EndsWith(".png") || path.EndsWith(".svg"))
            {
                TimeSpan maxAge = new TimeSpan(7, 0, 0, 0);
                r.Context.Response.Headers.Append("Cache-Control", "max-age=" + maxAge.TotalSeconds.ToString("0"));
            }
        }
});