Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 495
dfmetro Avatar asked Jun 08 '16 15:06

dfmetro


People also ask

Can CSS be cached?

Unless you've messed with your server, yes it's cached. All the browsers are supposed to handle it the same. Some people (like me) might have their browsers configured so that it doesn't cache any files though. Closing the browser doesn't invalidate the file in the cache.

How do I cache in asp net?

To manually cache application data, you can use the MemoryCache class in ASP.NET. ASP.NET also supports output caching, which stores the generated output of pages, controls, and HTTP responses in memory. You can configure output caching declaratively in an ASP.NET Web page or by using settings in the Web. config file.


2 Answers

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();
        });
like image 69
RonC Avatar answered Nov 16 '22 20:11

RonC


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;
like image 26
Mehmet Topçu Avatar answered Nov 16 '22 19:11

Mehmet Topçu