I was thinking to write an HttpModule for IIS7 and wanted a simple, useful and easily understandable scenario. Working with IIS customers for last 3 years one of those common scenario came into my mind, Redirecting http traffic to https. Although this is pretty straight forward requirement, till IIS6 it was difficult to achieve. Check the following KB 839357 (specifically for OWA scenario) which explains the cumbersome steps .
(If you are looking for same functionality in prior versions of IIS, find it at the bottom of this post)
HttpModules are not something new if you are an ASP.NET developer. But there are some differences. In IIS7 because of integrated pipeline, HttpModule applies to any request not just ASP.NET and that includes htm,jpg,asp,aspx,asmx,php,jsp...
So let us get into action (I'm using C# for this sample)
// register for the BeginRequest eventapplication.BeginRequest += new EventHandler(OnBeginRequest);
//BeginRequest implementationpublic void OnBeginRequest(Object sender, EventArgs e){HttpApplication app = (HttpApplication)sender;string HttpUrl = app.Request.Url.ToString();
if (HttpUrl.StartsWith("http:")) //Redirection done only if URL starts with http:{ HttpUrl = HttpUrl.Replace("http:", "https:"); app.Response.Redirect(HttpUrl.ToString(), true); //Redirecting (http 302) to the same URL but with https app.Response.End(); //We don't want to any further so end}}
Your http to https redirection sample is ready!!!
How to deploy the HttpModuleThere are multiple ways you can deploy this component (I'm assuming that it's being deployed for "default website")
Method 1Create a folder called "App_Code" inside "%systemdrive%\inetpub\wwwroot"Copy "redir.cs" file into "App_Code" folderCopy "web.config" file inside "%systemdrive%\inetpub\wwwroot"
Method 2Create a folder called "bin" inside "%systemdrive%\inetpub\wwwroot"Compile "redir.cs" into "redir.dll" and copy it into "bin" folder (to compile -> csc.exe /out:redir.dll /target:library redir.cs)Copy "web.config" file inside "%systemdrive%\inetpub\wwwroot"
If you open IIS7 UI and go to Modules you can see your HttpModule listed there.
Redirection options for prior versions of IIS below (you need to search for these)
- ASP.NET URL mapping capability (HttpContext.RewritePath)- IIS v6.0 Resource Kit includes the UrlRemap tool- IISRewrite - ISAPI_Rewrite - includes a "lite" version available for free. - Mod_Rewrite 2- Ionic's ISAPI Rewrite Filter