If you are not familiar with tilde usage in ASP.NET, then you are totally missing out. Often, our development environment is totally different than a production server. We may test our application using a virtual directory on our development machine, but may publish it to a dedicated root site.
So when you add an image or a link, you must always be aware of the type of the path you provide - relative, absolute, etc. Well, one of the best little tricks of ASP.NET is the tilde (~). This is essentially a shortcut for the
HttpRuntime.AppDomainAppVirtualPath property, which refers to the virtual application root, not the root of the web server.
While the tilde is quick and clean, it's also quite limited. For one, it is only useful when setting paths for certain controls that know how to resolve the path before rendering. So not only is it useful only in pre-defined areas of ASP.NET, it absolutely cannot be used outside any file not managed by the ASP.NET process. Until now.
One of the problems I often run into is when I am setting a path for something in a non ASP.NET file, such as a CSS file. For instance, I want to set the background-image attribute for a style in a CSS file, but unless I use a relative path, I’m screwed. I would usually end up just adding the background-image attribute directly to the tag instead of putting it into a CSS file. I’ll be the first to admit this is a lame workaround.
This article assumes a basic understanding of HTTP Handlers.
Using the code
For the sake of this article, I'm going to use CSS files as an example, although this technique could easily be applied to any type of file whose contents need to be resolved.
Currently, one might use the following tag to link a stylesheet to a .aspx page.
<link rel="stylesheet" href="resources/stylesheet.css" />
Once I've implemented the solution below, the same
link tag will look like this:
<link rel="stylesheet" href="~/resources/stylesheet.css.ashx" />
As you can see, there was a minor change with the appendage of ".ashx" onto the file path. This tells the FileResolver to resolve any virtual app path inside this CSS file.
Another small change is that now we can use the tilde in the file path for the CSS file. As you'll see later on, the HTTP Handler will resolve this path for the CSS file automatically. However, this does not seem to be the case in ASP.NET 1.1. So for ASP.NET 1.1, you may have to use a real relative or absolute path.
So, let's take a look at the guts of the FileResolver handler.
public class FileResolver : IHttpHandler
Now, let's look at each part of the preceding code.
CacheItem is an internal class designated to hold the resolved content of the CSS file. It also has a
DateEntered property tied to the content that is set to the last date and time the content was updated. This is useful in determining whether or not we need to serve up a new, fresh version of the CSS file content to a client.
ProcessRequest is a method that must be implemented for any class that implements the
IHttpHandler. It also contains the bulk of the logic for this handler.
ProcessRequest method, we know what file is being handled from the
HttpContext.Request.PhysicalPath property. We will do an initial check to ensure that the path to the file has been resolved. Once we have the physical, mapped path of the file, we do an initial check just to make sure the file still exists on the file system.
string absFilePath = context.Request.PhysicalPath.Replace(".ashx", "");
if(absFilePath.IndexOf("~\\") > -1)
absFilePath = absFilePath.Replace("~", "").Replace("\\\\", "\\");
context.Response.StatusCode = 404;
Once verified, we need to check the page's cache to see if a related
CacheItem has already been added. Once an initial request is made to this CSS file, a
CacheItem is created and stored.
CacheItem exists, we compare the
DateEntered value against the
If-Modified-Since header value from the request. If the dates match, then we know that the client has the latest version of the file already cached on their end. If the dates don't match or no appropriate header is found, we attempt to add the header and will write fresh content to the client.
FileCacheItem ci = (FileCacheItem)context.Cache[absFilePath];
if(ci != null)
if(context.Request.Headers["If-Modified-Since"] != null)
DateTime date = DateTime.Parse(
if(ci.DateEntered.ToString() == date.ToString())
context.Response.StatusCode = 304;
context.Response.StatusDescription = "Not Modified";
ci = UpdateFileCache(context, absFilePath);
context.Response.ContentType = "text/" +
CacheItem is not found, we need to update the cache with a new
CacheItem. This consists of reading the content from the CSS file and replacing any instance of the tilde shortcut with a true application path. Then, we'll package the new content into a
CacheItem and store it in the page cache.
private FileCacheItem UpdateFileCache(HttpContext context,
using(FileStream fs = new FileStream(filePath,
using(StreamReader sr = new StreamReader(fs))
content = sr.ReadToEnd();
string relAppPath = HttpRuntime.AppDomainAppVirtualPath;
relAppPath += "/";
content = content.Replace("~/", relAppPath);
FileCacheItem ci = new FileCacheItem(content);
CacheDependency cd = new CacheDependency(filePath);
context.Cache.Insert(filePath, ci, cd);
That's pretty much all there is to it. Like all handlers, they won't work until you add a few additional entries to your web.config. Not only is this necessary, but this is where we get to do a little configuration to extend the FileResolver to support any file types we want.
<add verb="GET" path="*.css.ashx"
<add verb="GET" path="*.js.ashx"
Props to Jon Gilkison for the collaboration efforts leading to this solution.