Don't you just hate it when you release some CSS to a live site but the client's browser doesn't pull down the latest version and the site they see looks horrific?
This article talks you through a simple control I have created that forces the browser to retrieve the latest version of a CSS include.
Using the Code
From a usage point of view, we just need to drag and drop the control from the toolbox. The user specific properties can be set either during design time or runtime.
Below is the markup that will need to be used in your ASP.NET Web Form or User Control:
<CWeb:CSSInclude ID="CSSInclude1" runat="server"
Rel="stylesheet" Type="text/css" CacheKey="BaseCSS" />
The properties supported by the control are:
HRef - Gets or sets the
href to the CSS file in the resulting link element.
Rel - Gets or sets the
rel for the resulting link element.
Type - Gets or sets the type for the resulting link element.
CacheKey - Gets or sets the cache key name to be used to store version information about the CSS file in the cache.
The control creates a date stamp based on the last write time to the file. This date stamp is then stored in the cache and a cache dependency is created against the CSS file. When the file changes, the date stamp will change, therefore the client will get the latest stylesheet.
Below is the code used to get the version information for the file:
private string GetIncludeUrlWithVersion()
string url = string.Empty;
string version = "1";
throw new ArgumentException("The cacheKey must have a value.");
if (Page.Cache[CacheKey] == null)
FileInfo fileInfo = new FileInfo(Page.Server.MapPath(HRef));
version = fileInfo.LastWriteTime.ToString("ddMMyyyyhhmmss");
CacheDependency cacheDependency = new CacheDependency(fileInfo.FullName);
Page.Cache.Insert(CacheKey, version, cacheDependency,);
version = Page.Cache[CacheKey] as string;
return ResolveUrl(HRef) + "?v=" + version;
Points of Interest
The same technique could also be used with script includes to force the browser to pull down the latest versions of js files. The caching issue could also be prevented through the client browser, through IIS, or by adding custom headers to the outgoing response. The technique I have described here is just another way of achieving the same result :)
- 14th January, 2010: Initial version.