ASP.NET WebForms URL Routing
<p>ASP.NET (4.0)//IIS7</p>

<p>I have a question in regard to url rewrite. I am working on a new application that already has some aspx files. I want to rewrite them to all route to a new page (Generic) that can handle all possible combinations by relying on a keyed parameter that map automatically to a configuration that can be pulled dynamically.</p>

<p>For instance, any request </p>

<ol>
<li>a.aspx?OriginalQuerstring              ==> Re routed to Default.aspx?$Key=1&amp;OriginalQuerstring</li>
<li>b.aspx?OriginalQuerstring              ==> Re routed to Default.aspx?$Key=2&amp;OriginalQuerstring</li>
<li>c.aspx?OriginalQuerstring              ==> Re routed to Default.aspx?$Key=3&amp;OriginalQuerstring</li>
<li>Default.aspx?$Key=1&amp;OriginalQuerstring ==> No routing, it passes through.</li>
</ol>

<p>Of course the original file names a.aspx, b.aspx, c.aspx are just to illustrate my point. I know an HttpModule can handle that. However, I am thinking with ASP.NET routing, it might be easier and more preferable. </p>

<p>As I indicated, an httpModule will do. I am looking for something else. </p>

<pre><code>    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    namespace WebApplication1
    {
      public class RewriteModule : IHttpModule
      {
        private static readonly Dictionary&lt;string, int&gt; oldPages = new Dictionary&lt;string, int&gt;(StringComparer.OrdinalIgnoreCase)
                    {
                      {"a.aspx", 1},
                      {"b.aspx", 2},
                      {"c.aspx", 3}
                    };

        public void Dispose()
        {
        }

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

        void context_BeginRequest(object sender, EventArgs e)
        {
          HttpApplication application = (HttpApplication)sender;
          HttpContext context = application.Context;
          string fileName = System.IO.Path.GetFileName(context.Request.PhysicalPath);
          int key;
          if (oldPages.TryGetValue(fileName, out key))
          {
            var nvc = HttpUtility.ParseQueryString(context.Request.Url.Query);
            nvc["$Key"] = key.ToString();
            context.Server.Transfer("~/Default.aspx?" + nvc.ToString());
          }
        }
      }
    }
</code></pre>
