6 out of 26 rated this helpful Rate this topic

How to: Use Routing with Web Forms

Visual Studio 2008

Updated: April 2009

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.

Date

History

Reason

April 2009

Added explanation of how to access values of URL parameters.

Customer feedback.

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
URL Routing in ASP.NET3.5
Check this Article:
http://www.mindstick.com/Articles/9992a0bc-90f5-4f04-823a-31f901b61643/?URL%20Routing%20in%20ASP%20Net%203%205%20IIS7
.Net Routing with Web Forms
I wrote a couple of blog posts about .net routing with web forms which might be of use:

http://jonlanceley.blogspot.com/2011/06/adding-net-routing-35-to-aspnet-web.html

http://jonlanceley.blogspot.com/2011/06/net-routing-35-route-to-directories.html

Differences for framework 4.0?
The UrlRoutingHandler is in System.Web version 2.0.&nbsp; Should I still reference that version in my config if my application is a 4.0 project?

[Tom Dykstra - MSFT] No. for a 4.0 project refer to the 4.0 version of this document.
Make sure HTTP Redirection feature is enabled for IIS
Routing won't work if HTTP Redirection is not installed.  Open Control Panel / Programs / Turn Windows Features on or off

Look under World Wide Web Services / Common HTTP Features

Check HTTP Redirection

http://blogs.msdn.com/b/rjacobs/archive/2010/06/30/system-web-routing-routetable-not-working-with-iis.aspx
Must set wildcard mapping on IIS 6!
What this article doesn't say - and what kept me trying again and again for 10 hours - is that by default, routing will never work as the routing url won't get to the ASP.net engine!!!

This is because IIS 6 only maps .aspx files to the ASP.net engine, so e.g. this will NOT be handled by ASP.net: www.yourdomain.com/routingpattern
Only www.yourdomain.com/routingpattern.aspx will be handled by ASP.net engine.

Simplest solution (especially on shared hosts) is to let all your routes contain an .aspx ending, but this is ugly.
Alternative is to ask your hosting provider to set a wildcard mapping to the ASP.net engine as described here:
  • http://haacked.com/archive/2008/11/26/asp.net-mvc-on-iis-6-walkthrough.aspx     (scroll down to "IIS6 Extension-less URLs")
  • http://blog.stevensanderson.com/2008/07/04/options-for-deploying-aspnet-mvc-to-iis-6/     (option 1)

Then all requests to your site including www.yourdomain.com/routingpattern will be handled by ASP.net engine. Note: This solution has a performance problem (solved by ASP.net 4), as described here:

  • http://blogs.msdn.com/b/tmarq/archive/2010/04/01/asp-net-4-0-enables-routing-of-extensionless-urls-without-impacting-static-requests.aspx
ASP.Net 3.5 sp1 and 4.0
It should be noted that there is no need to create a custom handler to add routes in ASP.Net 4.0. I would say that this article is especially usefull for ASP.Net 3.5 sp1.

Greetz

http://twitter.com/ceesva
Security!

You should be aware that standard asp.net url-authorization will be broken when using routing, since the requested url isn't the one actually being served!

Also note that page relative paths to stylesheets and scripts must be rebased, or the browser can't find them.

And Page.PreviousPage will throw an exception (because the PreviousPage hidden field stores the url, and uses it as a valid path, which it isn't).

BuildManager namespace
The BuildManager class used in the above example is in the System.Web.Compilation namespace.