Community Pick: Many members of our community have endorsed this article.
Editor's Choice: This article has been selected by our editors as an exceptional contribution.

URL Routing with reverse rewriting with Framework 3.5 sp1

JarrodDeveloper of Stuff
Published:
Updated:


Introduction

This article will explain how to use URL Routing dot Net Framework 3.5 sp1 (and I guessing eventually framework 4) and C# ASP .NET. URL Routing is the ability to format your url strings into friendly names and using the data passed in as if they were parameters passed to your page.

URL Routing is Microsoft’s answer for URL rewriting, and speaking from some sort of experience it is a lot easier and a lot less code than URL rewriting as well.

Why? You might ask... Simple reason – Search Engines rates your site higher than sites which still use query strings.

Starting out

A few things you need to do in order to use URL Routing (in VS 2008 sp1) :

1.    You need to make reference to “System.Web.Routing” (this came with Framework3.5 sp1)
2.    You need to have a web.config file (should be there by default unless you have nuked it)
3.    You need a Global.asax file
4.    You need the 2 Helper classes that I have written to ensure that the app works. The are very simple files and you can create your own or mod the simple ones I have created.

        a.    IRoutablePage.cs
        b.    RoutingHandler.cs
5.    In the web.config file add the following line to <httpModules> in <system.web>

<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />

Open in new window


 Note:  this will eventually need to be modified to run with framework 4.0, 4.5, 4.6, 4.7 etc... J
6.    Then change  the following in the <system.webServer> section of the config file.

<modules runAllManagedModulesForAllRequests="true">

Open in new window


7.    You need to add the following in the <system.webServer> section of the config file in order for IIS7 to understand the hosting options.

<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />

Open in new window



Getting into it

Now that your setup is semi-complete we can get onto the good stuff.
Go into your global.asax file and add the following:

public static void RegisterRoutes(RouteCollection routes)
                              {
                                  // StopRoutingHandler for .axd and .asmx requests
                                  routes.Add( new Route( "{resource}.axd/{*pathInfo}", new StopRoutingHandler() ) );
                                  routes.Add( new Route( "{service}.asmx/{*pathInfo}", new StopRoutingHandler() ) );
                       
                                  // Add some named handlers
                                  routes.Add("Blog", new Route("Blog/{entrydate}", new RoutingHandler("~/Blogs/ViewBlog.aspx")));
                              }

Open in new window


RegisterRoutes is going to be the default Microsoft function name and signature in the future releases. The first 2 lines of code there are saying that we want to add to our route table (by the way – this is how routes are managed using URL Routing) routes for all files that end with .axd and asmx. Then we are saying (with: StopRoutingHandler) that our URL Routing should ignore these types of files.

In the last line of code we add a route called “Blog” and we want all urls that look like “Blog/xxxxxx” to map to the Page Path ~/Blogs/ViewBlog.aspx. We are also declaring a variable called entrydate. We could of added more by doing something like this: "Blog/{entrydate}/{username}/{second}".

RoutingHandler is my custom implementation of IRouteHandler which is the 2nd paramater required to create a Route object.

Finally to start this whole thing off we need to call

RegisterRoutes(RouteTable.Routes);

Open in new window


From our application_start function.

The only thing left to do is ensure that Blogs/ViewBlog.aspx  implements IRoutablePage in the following way:

public partial class ViewBlog : Page, IRoutablePage
                          {                   
                              /// <summary>
                              /// Implementation of IRoutablePage
                              /// </summary>
                      
                              public RouteValueDictionary RouteData { get; set; }

Open in new window

Using the Variables from c# code

Then using the variables from the page is also very simple. If the url was http://blablabla.com/Blog/24 the value of RouteData["entrydate"] would be 24.

protected void Page_Load(object sender, EventArgs e)
                              {
                                  Response.Write("Wassup " + RouteData["entrydate"]);
                              }

Open in new window



I have uploaded a very simple and small project for demonstration.

Reverse writing the URL


A function called ReverseWriteUrl has been added to the global.asax file. What this does is reverse writes the URL for you. So if someone types into the address bar http://.../Blogs/ViewBlog.aspx?entrydate=20090801&UserName=Jarrod this will be rewritten as /Blog/20090801/Jarrod etc...

All you need to do is call the function as follows:

protected void Application_BeginRequest(object sender, EventArgs e)
                              {
                                  ReversewriteUrl (HttpContext.Current);
                              }

Open in new window


This will then check your routing table and reverse write all direct page calls to the virtual directory.

Originally posted @ http://www.zadeveloper.com/Articles/31
3
10,124 Views
JarrodDeveloper of Stuff

Comments (0)

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.