jdecuyper.github.com

Blog entries

<< Blog entries

Use a IHttpModule to add a querystring parameter to all your aspx files

October 4, 2011

Ever wondered how to append the same querystring to all your URL's? Let's say you want to have "?CurrentMode=Mode1.config" added to all your ASPX files and you don't want to do that manually and be sure all links from your website include that configuration file? Well that can be done in .Net and surprisingly it is not a pain!

The custom module looks as follow:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MyModule
{
   public class RewriteModule : IHttpModule
   {
      public void Dispose()
      {
         throw new NotImplementedException();
      }

      public void Init(HttpApplication context)
      {
         context.BeginRequest += new EventHandler(OnBeginRequest);
      }

      public void OnBeginRequest(Object s, EventArgs e)
      {
         string url = HttpContext.Current.Request.Url.AbsolutePath;
         string cookie = String.Empty;
         if(urlLower.EndsWith(".aspx") {
            // Cookies are available at this point but no session values! 
            // you could start checking for cookies as follow: if(HttpContext.Current.Request.Cookies["CurrentMode"] != null) ...

           HttpContext.Current.RewritePath(url + "?PropertiesFile=module1.config");
         }
      }
    }
}

Note that the parameter PropertiesFile will not be visible inside the browser's URL box but it will be available to the page (and to the code behind).

Only drawback: no session object is available at this point in time, so your only salvation could be making use of some fresh cookies! The cookie trick comes from stewartml@stackoverflow.

Lastly, you need to force your application to pick your module and that must be done referencing it through the web.config file:

<system.web>
   <httpModules>
      <add name="RewriteModule" type="MyModule.RewriteModule" />
   </httpModules>
</system.web>
        

And to make the story complete, the specific application I was working on didn't support cookies and I ended up editing all those links manually, but I least I learned something new :)