Click here to Skip to main content
15,886,518 members
Articles / Web Development / CSS

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

Rate me:
Please Sign up or sign in to vote.
4.66/5 (17 votes)
10 Jan 20065 min read 113.5K   644   49  
Introduces a solution for using virtual app paths in non ASP.NET files.
#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

namespace FileResolverDemoWeb
{
	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


Written By
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

Comments and Discussions