Down and Dirty Routing
So you want to make yourself a .Net blog engine or something nice (PURL anyone)
that converts this: http://my.site.com/somepage/someVal into something like http://my.site.com/somepage.aspx?somevar=someVal
ASP.net routing is pretty daunting. lotsa junk out there and whatnot. Here’s the bigger deal though. It’s not that hard…
There are basically 3 steps. all of which can be gleaned from here
Step 1: Add the route to the Global.asax
public static void RegisterRoutes(RouteCollection routes) { routes.Add(new Route( "{Location}/{Name}" , new PGIRouteHandler("~/Public/Main.aspx") )); }
Step 2: Create the routing handler (this moves the data into the page variables)
this baby should go somewhere in your namespace but doesn’t necessarily have to leave the current path. (i like to keep my code a little organized)
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Compilation; using System.Web.Routing; using System.Web.UI; namespace Web.Code { public class PGIRouteHandler: IRouteHandler { public PGIRouteHandler(string virtualPath) { this.VirtualPath = virtualPath; } public string VirtualPath { get; private set; } public IHttpHandler GetHttpHandler(RequestContext rc) { foreach (var urlParm in rc.RouteData.Values) { //this is the bit that adds the info to the HttpContext.Items object rc.HttpContext.Items[urlParm.Key] = urlParm.Value; } var page = BuildManager.CreateInstanceFromVirtualPath (VirtualPath, typeof(Page)) as IHttpHandler; return page; } } }
Step 3: Add the code to the Page_Load of the target page (Public/Main.aspx in this case)
public partial class Main : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { var Location = HttpContext.Current.Items["Location"]; var Name = HttpContext.Current.Items["Name"]; } }
That’s about the size of it. This is really the fast way to the prize and in no way handles any security concerns that may arise.
Happy Coding.
