Getting ASP.NET Routing Up and Running - The Definitive Guide

Back here I gave an example of setting up and ASP.NET webforms site to use ASP.NET routing. A few people have still run into trouble trying to get things working so I thought I'd try and boil things down to the bare essentials. This is what's required to get an ASP.NET webforms application routing requests via ASP.NET routing on ASP.NET 3.5 Sp1 using the WebDev WebServer.

Step 1

Create a new ASP.NET website

Step 2

Add a reference to System.Web.Routing

Step 3

Add Global.asax to your website

Step 4

Import the System.Web.Routing namespace in Global.asax

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

Step 5

Add code to the Application_Start method eg (in VB)

     Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
        ' Code that runs on application startup
        
        Dim rte = New Route("Routes/{ViewName}", New RouteHandler())

        RouteTable.Routes.Add(rte)
        
    End Sub

Step 6

Add your RouteHandler class eg

 Public Class RouteHandler
    Implements IRouteHandler

    Function GetHttpHandler(ByVal requestContext As System.Web.Routing.RequestContext) _
        As IHttpHandler Implements IRouteHandler.GetHttpHandler

        Dim v As New ViewHandler()
        v.ViewName = requestContext.RouteData.GetRequiredString("ViewName")
        Return v

    End Function

End Class

Step 7

Add the URLRoutingModule to the <httpModules> section in web.config eg

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

Step 8

You're done!

Routing Existing Files

Note that by default, ASP.NET routing gives preference to files that already exist on disk at the specified path - those will be served up without going through the routing mechanism unless you set the property RouteTable.Routes.RouteExistingFiles = True. This forces the routing mechanism to be invoked for existing files as well. To give an example:

Imagine I have a default.aspx file in the root of my website, a route defined with the pattern "{ViewName}" and RouteTable.Routes.RouteExistingFiles is False (the default).

If I make a request for https://mywebsite/default.aspx that will be served up in the "normal" way and the routing mechanism will not be invoked.

If I set RouteTable.Routes.RouteExistingFiles = True, the routing mechanism will be invoked and my RouteHandler will be called. The request will therefore be routed by ASP.NET routing.

If there was no route match for the request (eg imagine my only route pattern was "RouteMe/{ViewName}") then the routing mechanism would be invoked, no route match would be found and the default.aspx file would be served up in the normal way.

Technorati Tags: asp.net,routing