Click here to Skip to main content
Click here to Skip to main content
Articles » Web Development » ASP.NET » General » Downloads
 
Add your own
alternative version

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

, 10 Jan 2006
Introduces a solution for using virtual app paths in non ASP.NET files.
FileResolverDemoWeb2003.zip
images
bg_tile.gif
scripts
styles
FileResolverDemoWeb2005.zip
App_Code
bg_tile.gif
#region Usings

using System;
using System.IO;
using System.Configuration;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Caching;

#endregion

public class FileResolver : IHttpHandler
{
	/// <summary>
	/// File cache item used to store file content & date entered into cache
	/// </summary>
	internal class FileCacheItem
	{
		internal string Content;
		internal DateTime DateEntered = DateTime.Now;

		internal FileCacheItem(string content)
		{
			this.Content = content;
		}
	}

	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();
				sr.Close();
			}

			fs.Close();
		}

		//Get absolute application path
		string relAppPath = HttpRuntime.AppDomainAppVirtualPath;
		if(!relAppPath.EndsWith("/"))
			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;
	}

	public void ProcessRequest(HttpContext context)
	{
		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("\\\\", "\\");

		if(!File.Exists(absFilePath))
		{
			context.Response.StatusCode = 404;
			return;
		}

		FileCacheItem ci = (FileCacheItem)context.Cache[absFilePath];
		if(ci != null)
		{
			if(context.Request.Headers["If-Modified-Since"] != null)
			{
				try
				{
					DateTime date = DateTime.Parse(context.Request.Headers["If-Modified-Since"]);

					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";
						context.Response.End();
						return;
					}
				}
				catch(Exception){}
			}
			else
			{
				//In the event that the browser doesn't automatically have this header, add it
				context.Response.AddHeader("If-Modified-Since", ci.DateEntered.ToString());
			}
		}
		else
		{
			//Cache item not found, update cache
			ci = UpdateFileCache(context, absFilePath);
		}

		context.Response.Cache.SetLastModified(ci.DateEntered);
		context.Response.ContentType = "text/" + GetContentType(Path.GetExtension(absFilePath));
		context.Response.Write(ci.Content);
		context.Response.End();
	}

	/// <summary>
	/// Gets the appropriate content type for a specified extension
	/// </summary>
	private string GetContentType(string ext)
	{
		switch(ext.ToLower())
		{
			case ".css":
				return "css";
				break;
			case ".xml":
				return "xml";
				break;
			case ".js":
				return "javascript";
				break;
			default:
				return "plain";
				break;
		}
	}

	#region IHttpHandler Members

	public bool IsReusable
	{
		get
		{
			return true;
		}
	}

	#endregion
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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 http://www.csharper.net

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