14

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.

3
  • I'm not sure I understand 2). Can you restate the first part of that question? Commented Jun 8, 2016 at 16:21
  • I restated the question. Commented Jun 8, 2016 at 16:39
  • Thanks! I updated my answer based on the updated question. Commented Jun 8, 2016 at 18:18

3 Answers 3

33
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"));
            }
        }
});
Sign up to request clarification or add additional context in comments.

Comments

7

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

Comments

4

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.