Master Yoda
Master Yoda

Reputation: 4422

Adding client cache via httpmodule for custom folder

I am currently using within web.config of my project.

<location path="js">
  <system.webServer>
    <staticContent>
      <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="8765:00:00"/>
    </staticContent>
   </system.webServer>
</location>
<location path="css">
  <system.webServer>
    <staticContent>
      <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="8765:00:00"/>
    </staticContent>
   </system.webServer>
</location>

This would be fine if I only wanted to cache a few folders here and there but I have javascript and css in a number of other places that I also want to cache and have opted to use HttpModule to cache these directories there.

Ive been doing a bit of research and came across this article from Microsoft on clientCache which shows me how to update it in the httpModule using c#

  using(ServerManager serverManager = new ServerManager())
  { 
     Configuration config = serverManager.GetWebConfiguration("Default Web Site");
     ConfigurationSection staticContentSection = config.GetSection("system.webServer/staticContent");

     ConfigurationElement clientCacheElement = staticContentSection.GetChildElement("clientCache");
     clientCacheElement["cacheControlMode"] = @"UseMaxAge";
     clientCacheElement["cacheControlMaxAge"] = @"8765:00:00";

     serverManager.CommitChanges();
  }

My question is, is it possible to specify the exact folders I want to cache using this method? For example if I have a folder with javascript in the following directory: siteMap/js how do I tell my httpModule to set the clientCache for that explicit folder?

Upvotes: 0

Views: 137

Answers (1)

Jokies Ding
Jokies Ding

Reputation: 3494

For example. if you want to set clientcache for folder "Scripts" by adding section <location="Scripts"> in web.config.

Then you could try this config.GetSection("system.webServer/staticContent", "Scripts"); .

  using(ServerManager serverManager = new ServerManager()) { 
            Configuration config = serverManager.GetWebConfiguration("Default Web Site");

            ConfigurationSection staticContentSection = config.GetSection("system.webServer/staticContent", "Scripts");

            ConfigurationElement clientCacheElement = staticContentSection.GetChildElement("clientCache");
            clientCacheElement["cacheControlMode"] = @"UseMaxAge";
            clientCacheElement["cacheControlMaxAge"] = TimeSpan.Parse("8765.00:00:00");

            serverManager.CommitChanges();
        }
    }

Upvotes: 1

Related Questions