How to cache css,js or images files to asp.net cor

2020-06-17 04:57发布

问题:

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.

回答1:

Here is an approach that should work for you. This example sets css and js files to be cached for 7 days by the browser and sets non css, js, and images to have no cache headers. One other note, it's only necessary to set the cache control headers on the response is Asp.NET Core.

        app.Use(async (context, next) =>
        {
            string path = context.Request.Path;

            if(path.EndsWith(".css") || path.EndsWith(".js")) {

                //Set css and js files to be cached for 7 days
                TimeSpan maxAge = new TimeSpan(7, 0, 0, 0);     //7 days
                context.Response.Headers.Append("Cache-Control", "max-age="+ maxAge.TotalSeconds.ToString("0")); 

            } else if(path.EndsWith(".gif") || path.EndsWith(".jpg") || path.EndsWith(".png")) {
                //custom headers for images goes here if needed

            } else {
                //Request for views fall here.
                context.Response.Headers.Append("Cache-Control", "no-cache");
                context.Response.Headers.Append("Cache-Control", "private, no-store");

            }
            await next();
        });


回答2:

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


回答3:

Another solution via app.UseStaticFiles

 app.UseStaticFiles(new StaticFileOptions
        {
            OnPrepareResponse = ctx =>
            {
                const int durationInSeconds = 60 * 60 * 24;
                ctx.Context.Response.Headers[HeaderNames.CacheControl] =
                    "public,max-age=" + durationInSeconds;
            }
        });

You must add this library ;

using Microsoft.Net.Http.Headers;