With ASP.NET MVC comes a component that is called the routing engine. In ASP.NET MVC it is responsible to assign a controller to an incoming request:

image

From an conceptional view the routing engine consists of two parts:

a) The RouteTable which stores the information which routes are defined

b) The UrlRoutingModule which finds matches to routes on incoming requests.

image

But the routing engine is not limited to MVC in its use. The ASP.NET 3.5 Routing Engine is a powerful instrument for URLRewriting.

Lets have a look how to use routing standalone or with classic ASP.NET (wow, now its already classic! Never dreamed that this would happen so fast… But hey, the .NET platform is nearly ten years old…):

  1. First I added the HttpModule to you configuration file:
<httpModules>
  <add
   name="urlRouting"
   type="System.Web.Routing.UrlRoutingModule,
         System.Web.Routing,
         Version=3.5.0.0,
         Culture=neutral,
         PublicKeyToken=31BF3856AD364E35"/>
  1. Second I created a routing handler by implementing the IRouteHandler interface which comes from System.Web.Routing. I’ve put a simple if-else together to route to different pages:
using System.Web;
using System.Web.Compilation;
using System.Web.Routing;

namespace devcoach.Web
{
    public class RoutingPageHandler
        : IRouteHandler
    {
        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
         var VirtualPath = pathData.VirtualPath.Contains("articles")
                ? "~/Default.aspx"
                : "~/Default2.aspx";

            var handler = (IHttpHandler)BuildManager.CreateInstanceFromVirtualPath(
                VirtualPath,
                typeof(Page));

            return handler;
        }
    }
}
  1. Third I registered the routes to the RouteTable from within the Global.asax file:
<%@ Import Namespace="devcoach.Web"%>

<%@ Import Namespace="System.Web.Routing"%>

<%@ Application Language="C#" %>

 

<script runat="server">  

static void RegisterRoutes()
{
    RouteTable.Routes.Add(
        new Route(
            "articles",
            new RoutingPageHandler()));

    RouteTable.Routes.Add(
        new Route(
            "other",
            new RoutingPageHandler()));
}
void Application_Start(object sender, EventArgs e)
{
    RegisterRoutes();
} 

And here we go already:

image

Basic URL rewiting in a few minutes. Quite neat, eh. Definitely worth a try…