Click here to Skip to main content
15,897,151 members
Articles / Web Development / ASP.NET

Domain Forwarding with IHttpHandler

Rate me:
Please Sign up or sign in to vote.
3.50/5 (10 votes)
9 Sep 20031 min read 154.2K   897   67  
Use HttpHandlers to forward the user to different webpages depending on the requested hostname (domainname).
using System;
using System.Web;
using System.Diagnostics;
using System.Configuration;

namespace DomainFilter
{
	/// <summary>
	/// Summary description for HttpHandler.
	/// </summary>
	public class DomainHandler : IHttpHandler
	{
		/// <summary>
		/// Implementing IHttpHandler
		/// </summary>
		/// <param name="context"></param>
		public void ProcessRequest(HttpContext context) 
		{
			// Extract the host name from the request url
			// an look up the redirect url in the Web.config
			String redir = ConfigurationSettings.AppSettings[context.Request.Url.Host];
			if (redir != null)
			{
				// check for valid redirect url, preventing loops
				if (RedirectIsValid(redir, context.Request.Url))
				{
					// redirect the user to the url found in web.config
					context.Response.Redirect(redir, true);
				}
				else
				{
					// display an error.
					context.Response.Write("<h1><font color=red>Error invalid DomainHandler configuration</font></h1><br><b>Please check your Web.config file.</b>");
				}
			}
		}
		// prevents possible redirect loops
		// it is not allowed to have an redirect url targeting its self
		private bool RedirectIsValid(String redir, Uri currentUri)
		{
			String val1 = redir.ToLower();
			String url = currentUri.AbsoluteUri.ToLower();
			String host = currentUri.Host.ToLower();

			if (val1 == url)						{ return false; }			
			if (val1 == ( "http://" + host))		{ return false; }
			if (val1 == ("http://" + host + "/"))	{ return false;	}
			if (val1 == host)						{ return false;	}
			if (val1 == (host + "/"))				{ return false;	}

			return true;
		}
		/// <summary>
		/// Implementing IHttpHandler
		/// </summary>
		public bool IsReusable
		{
			get
			{
				return true;
			}
		}
	}
}

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
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions