0

We want browser caching on the content from certain folders on the site (images / styles / scripts) and setting them to remain fresh for 7 days. Also, we use a CMS called Ektron.

Here is the code we were using, any ideas as to why this isn't working?

From global.asax

void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
    System.Web.HttpCacheability cachelevel = System.Web.HttpCacheability.Private;

    if (Request.FilePath.ToLower().StartsWith("/images") || Request.FilePath.ToLower().StartsWith("/styles") || 
        Request.FilePath.ToLower().StartsWith("/js") || Request.FilePath.ToLower().StartsWith("/scripts"))
    {
        cachelevel = System.Web.HttpCacheability.Public;

        if (cachelevel == System.Web.HttpCacheability.Public) Response.Cache.SetCacheability(cachelevel);

        var staticExtensions = new List<string> { ".js", ".css", ".jpg", ".gif", ".png" };

        if (staticExtensions.Any(ext => Request.FilePath.ToLower().EndsWith(ext)))
        {
            Response.Cache.SetMaxAge(TimeSpan.FromDays(7));
        }
    }
2
  • How is it not working? Commented Sep 26, 2016 at 21:31
  • The content is not being cached, there's no difference in the headers, and everything is still set with maxage=0 and cache control is private. I believe it should be set as public and the max age=604800. Commented Sep 26, 2016 at 21:39

1 Answer 1

2

Don't think Application_PreSendRequestHeaders will not fire for every static content. Instead use the Web.config system.webServer - staticContent - clientCache setting, like this:

<system.webServer>
 <staticContent>
  <clientCache cacheControlMaxAge="7.00:00:00" cacheControlMode="UseMaxAge" />
 </staticContent>

This will set it to 7 days

Sign up to request clarification or add additional context in comments.

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.