Walkthrough: Using ASP.NET Routing in a Web Forms Application

This walkthrough shows how to modify an existing ASP.NET Web site to include ASP.NET routing features. At the end of this walkthrough the site will have three new Web pages. Hyperlinks in one of the new pages link to the other two pages by using routes. Because these hyperlinks use routing to create the link URLs, they do not need to be changed if the target pages change names or location.

This walkthrough shows how you can do the following with a minimum amount of code:

  • Define custom URL patterns that are not dependent on physical file names.

  • Generate URLs based on route URL parameter values by using markup or code.

  • In a routed page, retrieve values passed in URL segments by using markup or code.

A Visual Studio Web site project with source code is available to accompany this topic: Download.

Prerequisites

In order to run this walkthrough, you must have the following:

Creating Routes

Routes map URL patterns to physical files. To add routes to a Web site, you add them to the static (Shared in Visual Basic) Routes property of the RouteTable class by using the RouteCollection.MapPageRoute method.

In the following procedure, you create a method that you will use to add the routes. You call the new method from the Application_Start handler of the Global.asax page.

To add a method to the Global.asax file for adding routes

  1. If the Web site does not already have a Global.asax file, add one by following these steps:

    1. Right-click the Web project in Solution Explorer and then select Add New Item.

    2. Select Global Application Class and then click Add.

  2. Open the Global.asax file.

  3. After the Application directive, add an Import directive for the System.Web.Routing namespace, as shown in the following example:

    <%@ Import Namespace="System.Web.Routing" %>
    
    <%@ Import Namespace="System.Web.Routing" %>
    
  4. After the Session_End method, add the following code:

    Sub RegisterRoutes(ByVal routes As RouteCollection)
    End Sub
    
    void RegisterRoutes(RouteCollection routes)
    {
    }
    

    In the following procedure you will add code to this method that creates routes.

  5. In the Application_Start method, call RegisterRoutes as shown in the following example:

    Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
        RegisterRoutes(RouteTable.Routes)
    End Sub
    
    void Application_Start(object sender, EventArgs e)
    {
        RegisterRoutes(RouteTable.Routes);
    }
    

    This code passes the static (Shared in Visual Basic) Routes property of the RouteData class to RegisterRoutes.

The preceding procedure added an empty method that you can use to register routes. You will now add code to this method that adds routes to the Web site.

When you have finished this procedure, your application will accept URLs like the following:

  • https://server/application/SalesReportSummary/2009

  • https://server/application/SalesReport/en-US/2009

  • https://server/application/ExpensesRoute/

  • https://server/application/ExpensesRoute/2009/

  • https://server/application/ExpensesRoute/en-US/2009?extrafield=value

ASP.NET routing will route URLs such as these to the Sales.aspx and Expenses.aspx pages.

To add routes

  1. In the RegisterRoutes method, add the following code:

    routes.MapPageRoute("", _
        "SalesReportSummary/{year}", _
        "~/sales.aspx")
    
    routes.MapPageRoute("",
        "SalesReportSummary/{year}",
        "~/sales.aspx");
    

    This code adds an unnamed route that has a URL pattern that contains the literal value "SalesReportSummary" and a placeholder (URL parameter) named year. It maps the route to a file that is named Sales.aspx.

  2. In the RegisterRoutes method, add the following code:

    routes.MapPageRoute("SalesRoute", _
        "SalesReport/{locale}/{year}", _
        "~/sales.aspx")
    
    routes.MapPageRoute("SalesRoute",
        "SalesReport/{locale}/{year}",
        "~/sales.aspx");
    

    This code adds a route that is named SalesRoute. You are naming this route because it has the same parameter list as the route that you will create in the following step. Assigning names to these two routes enables you to differentiate them when you generate URLs for them.

  3. In the RegisterRoutes method, add the following code:

    routes.MapPageRoute("ExpensesRoute", _
        "ExpenseReport/{locale}/{year}/{*extrainfo}", _
        "~/expenses.aspx", True, _
        New RouteValueDictionary(New With _
            {.locale = "US", .year = DateTime.Now.Year.ToString()}), _
        New RouteValueDictionary(New With _
            {.locale = "[a-z]{2}", .year = "\d{4}"}))
    
    routes.MapPageRoute("ExpensesRoute",
        "ExpenseReport/{locale}/{year}/{*extrainfo}",
        "~/expenses.aspx", true,
        new RouteValueDictionary { 
            { "locale", "US" }, 
            { "year", DateTime.Now.Year.ToString() } },
        new RouteValueDictionary { 
            { "locale", "[a-z]{2}" }, 
            { "year", @"\d{4}" } });
    

    This code adds a route that is named ExpensesRoute. This route includes a catch-all parameter named extrainfo. The code sets the default value of the locale parameter to "US", and it sets the default value of the year parameter to the current year. Constraints specify that the locale parameter must consist of two alphabetic characters and the year parameter must consist of four numeric digits.

When you add hyperlinks to a Web page, if you want to specify a route URL instead of a physical file you have two options:

  • You can hard-code the route URL.

  • You can specify the route parameter names and values and let ASP.NET generate the URL that corresponds to them. You can also specify the route name if required in order to uniquely identify the route. If you change route URL patterns later, you would have to update any hard-coded URLs, but if you let ASP.NET generate the URLs, the correct URLs are always automatically generated (unless the parameters in the patterns are changed).

In the following procedure you add hyperlinks that use hard-coded URLs to a Web page.

To create hard-coded URLs

  1. In Solution Explorer, right-click the Web project and click Add New Item.

    The Add New Item dialog box is displayed.

  2. Select the Web Form template, make sure Place code in separate file is checked, set the name to Links.aspx, and then click Add.

    The Links.aspx page opens in Source view.

  3. Between the opening and closing <div> tags, add the following markup:

    <asp:HyperLink ID="HyperLink1" runat="server" 
        NavigateUrl="~/salesreportsummary/2010">
        Sales Report - All locales, 2010
    </asp:HyperLink>
    <br />
    <asp:HyperLink ID="HyperLink2" runat="server" 
        NavigateUrl="~/salesreport/WA/2011">
        Sales Report - WA, 2011
    </asp:HyperLink>
    <br />
    <asp:HyperLink ID="HyperLink3" runat="server" 
        NavigateUrl="~/expensereport">
        Expense Report - Default Locale and Year (US, current year)
    </asp:HyperLink>
    <br />
    
    <asp:HyperLink ID="HyperLink1" runat="server" 
        NavigateUrl="~/salesreportsummary/2010">
        Sales Report - All locales, 2010
    </asp:HyperLink>
    <br />
    <asp:HyperLink ID="HyperLink2" runat="server" 
        NavigateUrl="~/salesreport/WA/2011">
        Sales Report - WA, 2011
    </asp:HyperLink>
    <br />
    <asp:HyperLink ID="HyperLink3" runat="server" 
        NavigateUrl="~/expensereport">
        Expense Report - Default Locale and Year (US, current year)
    </asp:HyperLink>
    <br />
    

    This markup creates three HyperLink controls with hard-coded URLs. The first hyperlink matches the URL pattern of the sales summary route, the second matches the route named SalesRoute, and the third matches the route named ExpensesRoute. Because no parameters are specified for the URL of the third hyperlink, the default values defined for that route will be passed to Expenses.aspx.

Next you will you add markup that creates hyperlinks that specify route parameters and route names to create route URLs.

To create automatically generated URLs by using markup

  • With Links.aspx still open in Source view, add the following code after the HyperLink controls that you created in the previous procedure:

    <asp:HyperLink ID="HyperLink4" runat="server" 
        NavigateUrl="<%$RouteUrl:year=2011%>">
        Sales Report - All locales, 2011
    </asp:HyperLink>
    <br />
    <asp:HyperLink ID="HyperLink5" runat="server" 
        NavigateUrl="<%$RouteUrl:locale=CA,year=2009,routename=salesroute%>">
        Sales Report - CA, 2009
    </asp:HyperLink>
    <br />
    
    <asp:HyperLink ID="HyperLink4" runat="server" 
        NavigateUrl="<%$RouteUrl:year=2011%>">
        Sales Report - All locales, 2011
    </asp:HyperLink>
    <br />
    <asp:HyperLink ID="HyperLink5" runat="server" 
        NavigateUrl="<%$RouteUrl:locale=CA,year=2009,routename=salesroute%>">
        Sales Report - CA, 2009
    </asp:HyperLink>
    <br />
    

    This markup uses RouteUrl expressions to create URLs for the routes that are named SalesSummaryRoute and SalesRoute. The second RouteUrl expression specifies the name of the route because the parameter list that is provided in the code could match either the ExpensesRoute URL pattern or the SalesRoute URL pattern. The ExpensesRoute URL pattern has an extrainfo placeholder which the SalesRoute URL pattern does not have, but extrainfo is a catch-all placeholder, which means it is optional.

In the following procedure you add markup that creates a hyperlink and you use code to generate a URL for the hyperlink by specifying route parameters and a route name.

To create automatically generated URLs by using code

  1. With Links.aspx still open in Source view, add the following code after the HyperLink control that you created in the previous procedure:

    <asp:HyperLink ID="HyperLink6" runat="server">
        Expense Report - CA, 2008
    </asp:HyperLink>
    <br />
    
    <asp:HyperLink ID="HyperLink6" runat="server">
        Expense Report - CA, 2008
    </asp:HyperLink>
    <br />
    

    This markup does not set the NavigateUrl property because that property will be set in code.

  2. In Solution Explorer, expand Links.aspx, and then open Links.aspx.vb or Links.aspx.cs.

  3. Add a using statement (Imports in Visual Basic) for the System.Web.Routing namespace, as shown in the following example:

    Imports System.Web.Routing
    
    using System.Web.Routing;
    
  4. In the Page_Load method, add the following code:

    Dim parameters As RouteValueDictionary
    parameters = New RouteValueDictionary(New With _
             {.locale = "CA", .year = "2008"})
    
    RouteValueDictionary parameters = 
        new RouteValueDictionary  
            { 
                {"locale", "CA" }, 
                { "year", "2008" } , 
                { "category", "recreation" }
            };
    

    This code creates an instance of the RouteValueDictionary class that contains three parameters. The third parameter is category, which is not in the URL pattern. Because it is not in the URL pattern, the category parameter and its value will be rendered as a query-string parameter.

  5. Following the code that you added in the previous step, add the following code:

    Dim vpd As VirtualPathData
    vpd = RouteTable.Routes.GetVirtualPath(Nothing, "ExpensesRoute", parameters)
    
    VirtualPathData vpd = 
        RouteTable.Routes.GetVirtualPath(null, "ExpensesRoute", parameters);
    

    This code instantiates a VirtualPathData object by calling the GetVirtualPath method of the RouteCollection class. Because the SalesRoute URL pattern and the ExpensesRoute URL pattern have similar placeholders, it calls the overload that accepts route name and specifies the ExpensesRoute value.

  6. Following the code that you added in the previous step, add the following code to set the NavigateUrl property of the hyperlink:

    HyperLink6.NavigateUrl = vpd.VirtualPath
    
    HyperLink6.NavigateUrl = vpd.VirtualPath;
    

Accessing URL Parameter Values in ASP.NET Pages

In an ASP.NET page that has been invoked by ASP.NET routing, you can retrieve the values of URL parameters in markup or in code. For example, the SalesReport route includes parameters named locale and year, and when a URL request that matches this pattern is received, code in the Sales.aspx page might need to pass the values of those parameters to a SQL query.

In the following procedure, you access URL parameter values by using markup. This method is useful for displaying parameter values in the Web page.

To access URL parameter values by using markup

  1. Right-click the Web project and click Add New Item.

    The Add New Item dialog box is displayed.

  2. Select the Web Form template and set the name to Expenses.aspx.

    The Expenses.aspx page opens in Source view.

  3. Add the following markup between the opening and closing <div> tags:

    <h1>
        Expense Report for 
        <asp:Literal ID="Literal1" 
          Text="<%$RouteValue:locale%>" 
          runat="server"></asp:Literal>, 
        <asp:Literal ID="Literal2" 
          Text="<%$RouteValue:year%>" 
          runat="server"></asp:Literal>
    </h1>
    
    <h1>
        Expense Report for
        <asp:Literal ID="Literal1" 
          Text="<%$RouteValue:locale%>" 
          runat="server"></asp:Literal>,
        <asp:Literal ID="Literal2" 
          Text="<%$RouteValue:year%>" 
          runat="server"></asp:Literal>
    </h1>
    

    This markup uses RouteValue expressions to extract and display the values of the URL parameters that are passed to the page.

In the following procedure you access parameter values by using code. This method is useful when you must process the data in some way, such as by translating null values to a default value as shown in this procedure, or by passing the information to a SQL query.

To access URL parameter values by using code

  1. Right-click the Web project and click Add New Item.

    The Add New Item dialog box is displayed.

  2. Select the Web Form template, make sure Place code in separate file is checked, set the name to Sales.aspx, and then click Add.

    The Sales.aspx page opens in Source view.

  3. Add the following markup between the opening and closing <div> tags:

    <h1>
        Sales Report for
        <asp:Literal ID="LocaleLiteral" runat="server"></asp:Literal>,
        <asp:Literal ID="YearLiteral" runat="server"></asp:Literal>
    </h1>
    
    <h1>
        Sales Report for
        <asp:Literal ID="LocaleLiteral" runat="server"></asp:Literal>,
        <asp:Literal ID="YearLiteral" runat="server"></asp:Literal>
    </h1>
    

    This markup includes Literal controls but does not set their Text properties because those properties will be set in code.

  4. In Solution Explorer, expand Sales.aspx and then open Sales.aspx.vb or Sales.aspx.cs.

  5. In the Page_Load method, add the following code to set the Text property of the first Literal control to one of the following values:

    • The literal All locales if the locale parameter is null.

    • The value of the locale parameter if the locale parameter is not null.

    If Page.RouteData.Values("locale") Is Nothing Then
        LocaleLiteral.Text = "All locales"
    Else
        LocaleLiteral.Text = Page.RouteData.Values("locale").ToString()
    End If
    
    LocaleLiteral.Text = Page.RouteData.Values["locale"] == null ?
        "All locales" : Page.RouteData.Values["locale"].ToString();
    
  6. In the Page_Load method, add the following code to set the Text property of the first Literal control to the value of the year URL parameter:

    YearLiteral.Text = Page.RouteData.Values("year").ToString()
    
    YearLiteral.Text = Page.RouteData.Values["year"].ToString();
    

Testing Routing

Now you can test routing.

To test routing

  1. In Solution Explorer, right-click Links.aspx and select View in Browser.

    The page is displayed in the browser, as shown in the following figure:

    Screen shot of Links.aspx page

  2. Click each hyperlink.

    Notice that each hyperlink goes to a page that has a heading that corresponds to the text of the hyperlink.

  3. Go back to the Links.aspx page, select your browser's View Source command, and examine the URLs for the last three hyperlinks.

    You see the following automatically generated URLs:

    • https://[server]/[application]/SalesReportSummary/2011

    • https://[server]/[application]/SalesReport/CA/2009

    • https://[server]/[application]/ExpenseReport/CA/2008?category=recreation

  4. Copy the URL that ends in SalesReport/CA/2009 to the Windows Clipboard and close the View Source window.

  5. Paste the URL into the browser's address bar, change CA to invalidlocale and 2009 to invalidyear, and then press ENTER.

    A page is displayed that is similar to the following figure:

    SalesReport.aspx showing invalid parameter values

    You see the Sales Report page that shows the values invalidlocale and invalidyear. Because you did not specify any constraints for the SalesRoute route, invalid data is accepted.

  6. Paste the URL into the browser's address bar again, change CA to invalidlocale, change 2009 to invalidyear, change SalesReport to ExpenseReport, and press Enter.

    A page is displayed that is similar to the following figure:

    Error when Expense Report URL fails constraints

    You see a "not found" error because the URL cannot be resolved to a route. The ExpenseReport route will accept only locale parameters that have two alphabetic characters, and year parameters that have four numeric digits.

Next Steps

A typical use for URL parameters is in database queries. You can provide the value of a URL parameter to a data source control in markup by using the asp:RouteParameter.element. For more information, see the RouteParameter class.

See Also

Tasks

How to: Construct URLs from Routes

How to: Access URL Parameters in a Routed Page

How to: Define Routes for Web Forms Applications

Reference

Route

PageRouteHandler

RouteData

Concepts

ASP.NET Routing