Web developer from Sydney Australia. Currently using asp.net, mvc where possible.

Saturday, April 17, 2010

ASP.NET Force the Browser to Really CACHE Content


Recently I have been optimizing the load time for our site Jobping. Getting the browser to really cache a file (not request that file for the duration specified) is something that always takes some time to get right.

So I just wanted to share the code to achieve it and hope it helps someone else out.

TimeSpan duration = TimeSpan.FromMinutes(cacheDurationInMinutes);
HttpCachePolicy cache = HttpContext.Current.Response.Cache;
cache.SetCacheability(HttpCacheability.Public);
cache.SetExpires(DateTime.Now.Add(duration));
cache.SetMaxAge(duration);
cache.AppendCacheExtension("must-revalidate, proxy-revalidate");

FieldInfo maxAgeField = cache.GetType().GetField("_maxAge", BindingFlags.Instance | BindingFlags.NonPublic);
maxAgeField.SetValue(cache, duration);

This will instruct the browser to store a copy of the url andfor the duration given. So be sure that this is applicable for your content before using this code (YMMV).




kick it on DotNetKicks.com

1 comment:

Govind Sharma said...

Encouraging good article!I hope the author more than to share some! Thanks!

Mechanical Seals