Click here to Skip to main content
12,621,492 members (34,784 online)
Click here to Skip to main content
Add your own
alternative version


49 bookmarked

Using the FileResolver to allow virtual application paths ( ~ ) in any file

, 10 Jan 2006
Rate this:
Please Sign up or sign in to vote.
Introduces a solution for using virtual app paths in non ASP.NET files.


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.

A couple ideas on how to solve this problem came to my mind. After some collaboration, a solid solution was established. The idea consists of using HTTP Handlers to intercept any requests made to resources, such as a CSS, or even a JavaScript file. The handler is then responsible for parsing the said file and delivering a "resolved" file to the client.


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.

namespace FileResolverDemoWeb
    public class FileResolver : IHttpHandler
        /// <span class="code-SummaryComment"><summary>

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.

In the 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 a tilde was used in the page to this file, replace it w/ the app path
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.

If the 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())
                //Don't do anything, nothing has 
                //changed since last request
                context.Response.StatusCode = 304;
                context.Response.StatusDescription = "Not Modified";
        //In the event that the browser doesn't 
        //automatically have this header, add it
    //Cache item not found, update cache
    ci = UpdateFileCache(context, absFilePath);

context.Response.ContentType = "text/" + 

If the 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, 
                                          string filePath)
    string content;

    using(FileStream fs = new FileStream(filePath, 
                          FileMode.Open, FileAccess.Read))
        using(StreamReader sr = new StreamReader(fs))
            content = sr.ReadToEnd();


    //Get absolute application path
    string relAppPath = HttpRuntime.AppDomainAppVirtualPath;
        relAppPath += "/";

    //Replace virtual paths w/ absolute path
    content = content.Replace("~/", relAppPath);

    FileCacheItem ci = new FileCacheItem(content);

    //Store the FileCacheItem in cache 
    //w/ a dependency on the file changing
    CacheDependency cd = new CacheDependency(filePath);
    context.Cache.Insert(filePath, ci, cd);
    return ci;

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" 
                  type="FileResolverDemoWeb.FileResolver,FileResolverDemoWeb" />
            <add verb="GET" path="*.js.ashx" 
                  type="FileResolverDemoWeb.FileResolver,FileResolverDemoWeb" />

In this scenario, I've chosen to resolve the content for the CSS as well as the JavaScript files. Good times.


Props to Jon Gilkison for the collaboration efforts leading to this solution.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Bobby DeRosa
Web Developer
United States United States
I currently work for a company in San Diego, CA authoring server controls.

Get the latest up to date code at

You may also be interested in...


Comments and Discussions

GeneralVB Pin
carlor7-Mar-09 1:30
membercarlor7-Mar-09 1:30 
GeneralProblems with apache forwarding and a trailing slash Pin
jakeschirm2-Dec-08 11:53
memberjakeschirm2-Dec-08 11:53 
GeneralVery Helpful Pin
Mike Ellison20-May-08 7:08
memberMike Ellison20-May-08 7:08 
GeneralBetter way of resolving relative urls Pin
M. Manovich9-Oct-07 8:58
memberM. Manovich9-Oct-07 8:58 
//Get absolute application path
string relAppPath = HttpRuntime.AppDomainAppVirtualPath;
relAppPath += "/";

//Replace virtual paths w/ absolute path
content = content.Replace("~/", relAppPath);

There is a better way of doing this - How to resolve relative url's without ResolveUrl[^]
GeneralChange to example.. Problem with Subfolder Call Pin
MelvinB9-Jan-07 4:47
memberMelvinB9-Jan-07 4:47 
GeneralCannot make it to work as &lt;link rel="stylesheet" href="~/resources/stylesheet.css.ashx" /> Pin
vlad19791-Jun-06 12:03
membervlad19791-Jun-06 12:03 
QuestionHow can I resolve my Server Control's virtual path at design time? Pin
dajianshi13-Apr-06 22:15
memberdajianshi13-Apr-06 22:15 
GeneralTheme Support Pin
lostxp2-Mar-06 0:49
memberlostxp2-Mar-06 0:49 
Questionhow to modify for handling .gif or .jpg Pin
Rac_1232-Feb-06 7:14
memberRac_1232-Feb-06 7:14 Type? Pin
SteveC-A927-Jan-06 10:57
memberSteveC-A927-Jan-06 10:57 
AnswerRe: .htc Type? Pin
SteveC-A927-Jan-06 11:10
memberSteveC-A927-Jan-06 11:10 
QuestionHow to use it? Pin
placek19-Jan-06 1:33
memberplacek19-Jan-06 1:33 
AnswerRe: How to use it? Pin
Bobby DeRosa19-Jan-06 5:17
memberBobby DeRosa19-Jan-06 5:17 
QuestionParse ~'s in a file? Pin
rball18-Jan-06 9:48
memberrball18-Jan-06 9:48 
AnswerRe: Parse ~'s in a file? Pin
Bobby DeRosa18-Jan-06 10:43
memberBobby DeRosa18-Jan-06 10:43 
GeneralRe: Parse ~'s in a file? Pin
n1ck0s20-Jan-06 0:58
membern1ck0s20-Jan-06 0:58 
GeneralNice 1 :) Pin
J. Gilkison17-Jan-06 12:05
memberJ. Gilkison17-Jan-06 12:05 
Generaldo not works with template Pin
carzel13-Jan-06 5:04
membercarzel13-Jan-06 5:04 
GeneralRe: do not works with template Pin
Bobby DeRosa13-Jan-06 5:22
memberBobby DeRosa13-Jan-06 5:22 
QuestionFileResolver withURLRewrite? Pin
Preky11-Jan-06 4:19
memberPreky11-Jan-06 4:19 
AnswerRe: FileResolver withURLRewrite? Pin
Bobby DeRosa11-Jan-06 6:09
memberBobby DeRosa11-Jan-06 6:09 
GeneralRe: FileResolver withURLRewrite? Pin
Preky11-Jan-06 21:50
memberPreky11-Jan-06 21:50 
GeneralRe: FileResolver withURLRewrite? Pin
Bobby DeRosa12-Jan-06 6:35
memberBobby DeRosa12-Jan-06 6:35 
GeneralRe: FileResolver withURLRewrite? Pin
Preky12-Jan-06 22:39
memberPreky12-Jan-06 22:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.161128.1 | Last Updated 10 Jan 2006
Article Copyright 2006 by Bobby DeRosa
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid