URL Routing
by Erik Reitan
Download Wingtip Toys Sample Project (C#) or Download E-book (PDF)
This tutorial series will teach you the basics of building an ASP.NET Web Forms application using ASP.NET 4.5 and Microsoft Visual Studio Express 2013 for Web. A Visual Studio 2013 project with C# source code is available to accompany this tutorial series.
In this tutorial, you will modify the Wingtip Toys sample application to support URL routing. Routing enables your web application to use URLs that are friendly, easier to remember, and better supported by search engines. This tutorial builds on the previous tutorial “Membership and Administration” and is part of the Wingtip Toys tutorial series.
What you’ll learn:
- How to register routes for an ASP.NET Web Forms application.
- How to add routes to a web page.
- How to select data from a database to support routes.
ASP.NET Routing Overview
URL routing allows you to configure an application to accept request URLs that do not map to physical files. A request URL is simply the URL a user enters into their browser to find a page on your web site. You use routing to define URLs that are semantically meaningful to users and that can help with search-engine optimization (SEO).
By default, the Web Forms template includes ASP.NET Friendly URLs. Much of the basic routing work will be implemented by using Friendly URLs. However, in this tutorial you will add customized routing capabilities.
Before customizing URL routing, the Wingtip Toys sample application can link to a product using the following URL:
https://localhost:44300/ProductDetails.aspx?productID=2
By customizing URL routing, the Wingtip Toys sample application will link to the same product using an easier to read URL:
https://localhost:44300/Product/Convertible%20Car
Routes
A route is a URL pattern that is mapped to a handler. The handler can be a physical file, such as an .aspx file in a Web Forms application. A handler can also be a class that processes the request. To define a route, you create an instance of the Route class by specifying the URL pattern, the handler, and optionally a name for the route.
You add the route to the application by adding the Route
object to the static Routes
property of the RouteTable
class. The Routes property is a RouteCollection
object that stores all the routes for the application.
URL Patterns
A URL pattern can contain literal values and variable placeholders (referred to as URL parameters). The literals and placeholders are located in segments of the URL which are delimited by the slash (/
) character.
When a request to your web application is made, the URL is parsed into segments and placeholders, and the variable values are provided to the request handler. This process is similar to the way the data in a query string is parsed and passed to the request handler. In both cases, variable information is included in the URL and passed to the handler in the form of key-value pairs. For query strings, both the keys and the values are in the URL. For routes, the keys are the placeholder names defined in the URL pattern, and only the values are in the URL.
In a URL pattern, you define placeholders by enclosing them in braces ( {
and }
). You can define more than one placeholder in a segment, but the placeholders must be separated by a literal value. For example, {language}-{country}/{action}
is a valid route pattern. However, {language}{country}/{action}
is not a valid pattern, because there is no literal value or delimiter between the placeholders. Therefore, routing cannot determine where to separate the value for the language placeholder from the value for the country placeholder.
Mapping and Registering Routes
Before you can include routes to pages of the Wingtip Toys sample application, you must register the routes when the application starts. To register the routes, you will modify the Application_Start
event handler.
- In Solution Explorerof Visual Studio, find and open the Global.asax.cs file.
Add the code highlighted in yellow to the Global.asax.cs file as follows:
[!code-csharpMain]
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Web;
5: using System.Web.Optimization;
6: using System.Web.Routing;
7: using System.Web.Security;
8: using System.Web.SessionState;
9: using System.Data.Entity;
10: using WingtipToys.Models;
11: using WingtipToys.Logic;
12:
13: namespace WingtipToys
14: {
15: public class Global : HttpApplication
16: {
17: void Application_Start(object sender, EventArgs e)
18: {
19: // Code that runs on application startup
20: RouteConfig.RegisterRoutes(RouteTable.Routes);
21: BundleConfig.RegisterBundles(BundleTable.Bundles);
22:
23: // Initialize the product database.
24: Database.SetInitializer(new ProductDatabaseInitializer());
25:
26: // Create custom role and user.
27: RoleActions roleActions = new RoleActions();
28: roleActions.AddUserAndRole();
29:
30: // Add Routes.
31: RegisterCustomRoutes(RouteTable.Routes);
32: }
33:
34: void RegisterCustomRoutes(RouteCollection routes)
35: {
36: routes.MapPageRoute(
37: "ProductsByCategoryRoute",
38: "Category/{categoryName}",
39: "~/ProductList.aspx"
40: );
41: routes.MapPageRoute(
42: "ProductByNameRoute",
43: "Product/{productName}",
44: "~/ProductDetails.aspx"
45: );
46: }
47: }
48: }
When the Wingtip Toys sample application starts, it calls the Application_Start
event handler. At the end of this event handler, the RegisterCustomRoutes
method is called. The RegisterCustomRoutes
method adds each route by calling the MapPageRoute
method of the RouteCollection
object. Routes are defined using a route name, a route URL and a physical URL.
The first parameter (“ProductsByCategoryRoute
”) is the route name. It is used to call the route when it is needed. The second parameter (“Category/{categoryName}
”) defines the friendly replacement URL that can be dynamic based on code. You use this route when you are populating a data control with links that are generated based on data. A route is shown as follows:
[!code-csharpMain]
1: routes.MapPageRoute(
2: "ProductsByCategoryRoute",
3: "Category/{categoryName}",
4: "~/ProductList.aspx"
5: );
The second parameter of the route includes a dynamic value specified by braces ({ }
). In this case, the categoryName
is a variable that will be used to determine the proper routing path.
[!NOTE]
Optional
You might find it easier to manage your code by moving the
RegisterCustomRoutes
method to a separate class. In the Logic folder, create a separateRouteActions
class. Move the aboveRegisterCustomRoutes
method from the Global.asax.cs file into the newRoutesActions
class. Use theRoleActions
class and thecreateAdmin
method as an example of how to call theRegisterCustomRoutes
method from the Global.asax.cs file.
You may also have noticed the RegisterRoutes
method call using the RouteConfig
object at the beginning of the Application_Start
event handler. This call is made to implement default routing. It was included as default code when you created the application using Visual Studio’s Web Forms template.
Retrieving and Using Route Data
As mentioned above, routes can be defined. The code that you added to the Application_Start
event handler in the Global.asax.cs file loads the definable routes.
Setting Routes
Routes require you to add additional code. In this tutorial, you will use model binding to retrieve a RouteValueDictionary
object that is used when generating the routes using data from a data control. The RouteValueDictionary
object will contain a list of product names that belong to a specific category of products. A link is created for each product based on the data and route.
Enable Routes for Categories and Products
Next, you’ll update the application to use the ProductsByCategoryRoute
to determine the correct route to include for each product category link. You’ll also update the ProductList.aspx page to include a routed link for each product. The links will be displayed as they were before the change, however the links will now use URL routing.
- In Solution Explorer, open the Site.Master page if it is not already open.
Update the ListView control named “
[!code-aspxMain]categoryList
” with the changes highlighted in yellow, so the markup appears as follows:1: <asp:ListView ID="categoryList"
2: ItemType="WingtipToys.Models.Category"
3: runat="server"
4: SelectMethod="GetCategories" >
5: <ItemTemplate>
6: <b style="font-size: large; font-style: normal">
7: <a href="<%#: GetRouteUrl("ProductsByCategoryRoute", new {categoryName = Item.CategoryName}) %>">
8: <%#: Item.CategoryName %>
9: </a>
10: </b>
11: </ItemTemplate>
12: <ItemSeparatorTemplate> | </ItemSeparatorTemplate>
13: </asp:ListView>
- In Solution Explorer, open the ProductList.aspx page.
Update the
[!code-aspxMain]ItemTemplate
element of the ProductList.aspx page with the updates highlighted in yellow, so the markup appears as follows:1: <ItemTemplate>
2: <td runat="server">
3: <table>
4: <tr>
5: <td>
6: <a href="<%#: GetRouteUrl("ProductByNameRoute", new {productName = Item.ProductName}) %>">
7: <image src='/Catalog/Images/Thumbs/<%#:Item.ImagePath%>'
8: width="100" height="75" border="1" />
9: </a>
10: </td>
11: </tr>
12: <tr>
13: <td>
14: <a href="<%#: GetRouteUrl("ProductByNameRoute", new {productName = Item.ProductName}) %>">
15: <%#:Item.ProductName%>
16: </a>
17: <br />
18: <span>
19: <b>Price: </b><%#:String.Format("{0:c}", Item.UnitPrice)%>
20: </span>
21: <br />
22: <a href="/AddToCart.aspx?productID=<%#:Item.ProductID %>">
23: <span class="ProductListItem">
24: <b>Add To Cart<b>
25: </span>
26: </a>
27: </td>
28: </tr>
29: <tr>
30: <td> </td>
31: </tr>
32: </table>
33: </p>
34: </td>
35: </ItemTemplate>
Open the code-behind of ProductList.aspx.cs and add the following namespace as highlighted in yellow:
[!code-csharpMain]1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Web;
5: using System.Web.UI;
6: using System.Web.UI.WebControls;
7: using WingtipToys.Models;
8: using System.Web.ModelBinding;
9: using System.Web.Routing;
Replace the
GetProducts
method of the code-behind (ProductList.aspx.cs) with the following code:[!code-csharpMain]
1: public IQueryable<Product> GetProducts(
2: [QueryString("id")] int? categoryId,
3: [RouteData] string categoryName)
4: {
5: var _db = new WingtipToys.Models.ProductContext();
6: IQueryable<Product> query = _db.Products;
7:
8: if (categoryId.HasValue && categoryId > 0)
9: {
10: query = query.Where(p => p.CategoryID == categoryId);
11: }
12:
13: if (!String.IsNullOrEmpty(categoryName))
14: {
15: query = query.Where(p =>
16: String.Compare(p.Category.CategoryName,
17: categoryName) == 0);
18: }
19: return query;
20: }
Add Code for Product Details
Now, update the code-behind (ProductDetails.aspx.cs) for the ProductDetails.aspx page to use route data. Notice that the new GetProduct
method also accepts a query string value for the case where the user has a link bookmarked that uses the older non-friendly, non-routed URL.
Replace the
GetProduct
method of the code-behind (ProductDetails.aspx.cs) with the following code:[!code-csharpMain]
1: public IQueryable<Product> GetProduct(
2: [QueryString("ProductID")] int? productId,
3: [RouteData] string productName)
4: {
5: var _db = new WingtipToys.Models.ProductContext();
6: IQueryable<Product> query = _db.Products;
7: if (productId.HasValue && productId > 0)
8: {
9: query = query.Where(p => p.ProductID == productId);
10: }
11: else if (!String.IsNullOrEmpty(productName))
12: {
13: query = query.Where(p =>
14: String.Compare(p.ProductName, productName) == 0);
15: }
16: else
17: {
18: query = null;
19: }
20: return query;
21: }
Running the Application
You can run the application now to see the updated routes.
- Press F5 to run the Wingtip Toys sample application.
The browser opens and shows the Default.aspx page. - Click the Products link at the top of the page.
All products are displayed on the ProductList.aspx page. The following URL (using your port number) is displayed for the browser:
https://localhost:44300/ProductList
- Next, click the Cars category link near the top of the page.
Only cars are displayed on the ProductList.aspx page. The following URL (using your port number) is displayed for the browser:
https://localhost:44300/Category/Cars
- Click the link containing the name of the first car listed on the page (“Convertible Car”) to display the product details.
The following URL (using your port number) is displayed for the browser:
https://localhost:44300/Product/Convertible%20Car
- Next, enter the following non-routed URL (using your port number) into the browser:
https://localhost:44300/ProductDetails.aspx?productID=2
The code still recognizes a URL that includes a query string, for the case where a user has a link bookmarked.
Summary
In this tutorial, you have added routes for categories and products. You have learned how routes can be integrated with data controls that use model binding. In the next tutorial, you will implement global error handling.
Additional Resources
ASP.NET Friendly URLs
Deploy a Secure ASP.NET Web Forms App with Membership, OAuth, and SQL Database to Azure App Service
Microsoft Azure - Free Trial
|