How to: Use Routing with Web Forms

ASP.NET routing enables you to handle URL requests that do not map to a physical file in the Web application. By default, ASP.NET routing is enabled in an ASP.NET application for Dynamic Data or the MVC framework, but routing is not enabled in ASP.NET Web site projects. Therefore, to use routing in an ASP.NET Web site, you must take steps to enable it.

To enable routing, you must change the configuration file for the application to register the routing assembly and to add the UrlRoutingModule class as a module. You must also create a custom route handler for the route. The handler implements the IRouteHandler interface and creates an instance of the Web form (the .aspx file) that will be the actual endpoint for the request. Finally, you must define the routes that are served by the handler. This topic shows how to perform these steps.

See a video that shows this feature: Watch.

To configure an ASP.NET Web site project for routing

  1. In the application's Web.config file, add the ASP.NET routing assembly to the assemblies element, as shown in the following example:

    <add assembly="System.Web.Routing, Version=3.5.0.0, 
      Culture=neutral, 
      PublicKeyToken=31BF3856AD364E35"/>
    
  2. If the application runs under IIS 6.0 or IIS 7.0 Classic mode, add the UrlRoutingModule class to the httpModules element, as shown in the following example:

    <httpModules>
      <add name="UrlRoutingModule" 
           type="System.Web.Routing.UrlRoutingModule, 
                 System.Web.Routing, 
                 Version=3.5.0.0, 
                 Culture=neutral, 
                 PublicKeyToken=31BF3856AD364E35"/>
    </httpModules>
    
  3. If the application runs under IIS 7.0 Integrated mode, add the UrlRoutingModule class to the modules element, as shown in the following example:

    <system.webServer>
      <modules>
        <remove name="UrlRoutingModule" />
        <add name="UrlRoutingModule" 
             type="System.Web.Routing.UrlRoutingModule, 
                   System.Web.Routing, 
                   Version=3.5.0.0, 
                   Culture=neutral, 
                   PublicKeyToken=31BF3856AD364E35"/>
      </modules>
    </system.webServer>
    
  4. If the application runs under IIS 7.0 Integrated mode, add the UrlRoutingHandler class to the handlers element as shown in the following example:

    <system.webServer>
      <handlers>
        <add name="UrlRoutingHandler" 
             preCondition="integratedMode" 
             verb="*" 
             path="UrlRouting.axd" 
             type="System.Web.HttpForbiddenHandler, 
                   System.Web, Version=2.0.0.0, 
                   Culture=neutral, 
                   PublicKeyToken=b03f5f7f11d50a3a" />
      </handlers>
    </system.webServer>
    

To create the handler

  1. Create a class that implements the IRouteHandler interface.

  2. Implement the GetHttpHandler method. To specify a particular Web Form (.aspx file) as the endpoint for the request, return an instance of that Web form from the GetHttpHandler method.

    The following example shows a class named CustomRouteHandler that implements the IRouteHandler interface. The GetHttpHandler method calls the CreateInstanceFromVirtualPath method to create an instance of the specified Web form. This instance is returned as the endpoint for the request.

    Public Class CustomRouteHandler
        Implements IRouteHandler
    
        Private _virtualPath As String
    
        Public Sub New(ByVal vPath As String)
            _virtualPath = vPath
        End Sub
    
        Public Property VirtualPath() As String
            Get
                Return _virtualPath
            End Get
            Private Set(ByVal value As String)
                _virtualPath = value
            End Set
        End Property
    
        Public Function GetHttpHandler(ByVal requestContext _
              As System.Web.Routing.RequestContext) _
              As System.Web.IHttpHandler _
              Implements System.Web.Routing.IRouteHandler.GetHttpHandler
            Dim redirectPage As IHttpHandler
            redirectPage = _
              BuildManager.CreateInstanceFromVirtualPath(VirtualPath, _
              GetType(Page))
            Return redirectPage
        End Function
    End Class
    
    public class CustomRouteHandler : IRouteHandler
    {
        public CustomRouteHandler(string virtualPath)
        {
            this.VirtualPath = virtualPath;
        }
    
        public string VirtualPath { get; private set; }
    
        public IHttpHandler GetHttpHandler(RequestContext 
              requestContext)
        {
            var page = BuildManager.CreateInstanceFromVirtualPath
                 (VirtualPath, typeof(Page)) as IHttpHandler;
            return page;
        }
    }
    

To register the custom handler

  1. If the Web application does not already have a Global.asax file, add it.

  2. Add a directive to the Global.asax file that imports the System.Web.Routing namespace, as shown in the following example:

    <%@ Import Namespace="System.Web.Routing" %>
    
  3. Create a method in the Global.asax file that adds the route definitions to the Routes property of the RouteTable class.

  4. Call that method from the Application_Start event handler.

    The following example shows a method that registers a class named CustomRouteHandler as the handler for requests that match bikes/sale.

    Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
        RegisterRoutes(RouteTable.Routes)
    End Sub
    
    Shared Sub RegisterRoutes(ByVal routes As RouteCollection)
        routes.Add("BikeSaleRoute", New Route _
        ( _
           "bikes/sale", New CustomRouteHandler("~/Contoso/Products/Details.aspx") _
        ))
    End Sub
    
    void Application_Start(object sender, EventArgs e) 
    {
        RegisterRoutes(RouteTable.Routes);
    }
    
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.Add("BikeSaleRoute", new Route
        (
           "bikes/sale", 
           new CustomRouteHandler("~/Contoso/Products/Details.aspx")
        ));
    }
    

To access URL parameters in a routed page

  • In the GetHttpHandler method of the custom handler, retrieve URL parameter values from the RequestContext object that is passed to the method, as shown in the following example:

    For Each urlParm In requestContext.RouteData.Values
        requestContext.HttpContext.Items(urlParm.Key) = urlParm.Value
    Next
    
    foreach (var urlParm in requestContext.RouteData.Values)
    {
        requestContext.HttpContext.Items[urlParm.Key] = urlParm.Value;
    }
    

    In the example, the parameter values are copied to the Items property of the HttpContext object in order to make them available to code written for the routed page.

See Also

Concepts

ASP.NET Routing

HTTP Handlers and HTTP Modules Overview

Change History

Date

History

Reason

April 2009

Added explanation of how to access values of URL parameters.

Customer feedback.