URL Routing (2024)

  • Article

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.

  1. In Solution Explorerof Visual Studio, find and open the Global.asax.cs file.

  2. Add the code highlighted in yellow to the Global.asax.cs file as follows:

    using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Optimization;using System.Web.Routing;using System.Web.Security;using System.Web.SessionState;using System.Data.Entity;using WingtipToys.Models;using WingtipToys.Logic;namespace WingtipToys{ public class Global : HttpApplication { void Application_Start(object sender, EventArgs e) { // Code that runs on application startup RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // Initialize the product database. Database.SetInitializer(new ProductDatabaseInitializer()); // Create custom role and user. RoleActions roleActions = new RoleActions(); roleActions.AddUserAndRole(); // Add Routes. RegisterCustomRoutes(RouteTable.Routes); } void RegisterCustomRoutes(RouteCollection routes) { routes.MapPageRoute( "ProductsByCategoryRoute", "Category/{categoryName}", "~/ProductList.aspx" ); routes.MapPageRoute( "ProductByNameRoute", "Product/{productName}", "~/ProductDetails.aspx" ); } }}

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:

routes.MapPageRoute( "ProductsByCategoryRoute", "Category/{categoryName}", "~/ProductList.aspx" );

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 separate RouteActions class. Move the above RegisterCustomRoutes method from the Global.asax.cs file into the new RoutesActions class. Use the RoleActions class and the createAdmin method as an example of how to call the RegisterCustomRoutes 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.

  1. In Solution Explorer, open the Site.Master page if it is not already open.

  2. Update the ListView control named "categoryList" with the changes highlighted in yellow, so the markup appears as follows:

    <asp:ListView ID="categoryList" ItemType="WingtipToys.Models.Category" runat="server" SelectMethod="GetCategories" > <ItemTemplate> <b style="font-size: large; font-style: normal"> <a href="<%#: GetRouteUrl("ProductsByCategoryRoute", new {categoryName = Item.CategoryName}) %>"> <%#: Item.CategoryName %> </a> </b> </ItemTemplate> <ItemSeparatorTemplate> | </ItemSeparatorTemplate></asp:ListView>
  3. In Solution Explorer, open the ProductList.aspx page.

  4. Update the ItemTemplate element of the ProductList.aspx page with the updates highlighted in yellow, so the markup appears as follows:

    <ItemTemplate> <td runat="server"> <table> <tr> <td> <a href="<%#: GetRouteUrl("ProductByNameRoute", new {productName = Item.ProductName}) %>"> <image src='/Catalog/Images/Thumbs/<%#:Item.ImagePath%>' width="100" height="75" border="1" /> </a> </td> </tr> <tr> <td> <a href="<%#: GetRouteUrl("ProductByNameRoute", new {productName = Item.ProductName}) %>"> <%#:Item.ProductName%> </a> <br /> <span> <b>Price: </b><%#:String.Format("{0:c}", Item.UnitPrice)%> </span> <br /> <a href="/AddToCart.aspx?productID=<%#:Item.ProductID %>"> <span class="ProductListItem"> <b>Add To Cart<b> </span> </a> </td> </tr> <tr> <td>&nbsp;</td> </tr> </table> </p> </td></ItemTemplate>
  5. Open the code-behind of ProductList.aspx.cs and add the following namespace as highlighted in yellow:

    using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using WingtipToys.Models;using System.Web.ModelBinding;using System.Web.Routing;
  6. Replace the GetProducts method of the code-behind (ProductList.aspx.cs) with the following code:

    public IQueryable<Product> GetProducts( [QueryString("id")] int? categoryId, [RouteData] string categoryName){ var _db = new WingtipToys.Models.ProductContext(); IQueryable<Product> query = _db.Products; if (categoryId.HasValue && categoryId > 0) { query = query.Where(p => p.CategoryID == categoryId); } if (!String.IsNullOrEmpty(categoryName)) { query = query.Where(p => String.Compare(p.Category.CategoryName, categoryName) == 0); } return query;}

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.

  1. Replace the GetProduct method of the code-behind (ProductDetails.aspx.cs) with the following code:

    public IQueryable<Product> GetProduct( [QueryString("ProductID")] int? productId, [RouteData] string productName){ var _db = new WingtipToys.Models.ProductContext(); IQueryable<Product> query = _db.Products; if (productId.HasValue && productId > 0) { query = query.Where(p => p.ProductID == productId); } else if (!String.IsNullOrEmpty(productName)) { query = query.Where(p => String.Compare(p.ProductName, productName) == 0); } else { query = null; } return query;}

Running the Application

You can run the application now to see the updated routes.

  1. Press F5 to run the Wingtip Toys sample application.
    The browser opens and shows the Default.aspx page.
  2. 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
  3. 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
  4. 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
  5. 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

URL Routing (2024)

FAQs

What does URL routing mean? ›

URL routing refers to mapping URLs (Uniform Resource Locators) to the appropriate handlers or controllers within a web application. The mechanism directs incoming requests to their destinations based on predefined rules and patterns.

What is the route of a URL? ›

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.

What is the URL path route? ›

URL Path Based Routing allows you to route traffic to backend server pools based on URL Paths of the request. One of the scenarios is to route requests for different content types to different backend server pools.

What is the difference between URL and route? ›

A URL is a destination. A route is how you navigate to get there.

What does URL pattern do? ›

A URL pattern is a set of ordered characters that is modeled after an actual URL. The URL pattern is used to match one or more specific URLs.

What is the difference between link and routing? ›

Link is dependent to Route's locations. But Route can be used without Link. In Layman's terms we could understand the difference as mentioned below: a)Routes are responsible for rendering UI when its path matches current URL where as Links are similar to anchor tags in HTML which are used to access the route paths.

How do I find my URL? ›

On your computer, go to google.com. Search for the page. At the top of your browser, click the address bar to select the entire URL. Copy.

What is an URL example? ›

Most web browsers display the URL of a web page above the page in an address bar. A typical URL could have the form http://www.example.com/index.html , which indicates a protocol ( http ), a hostname ( www.example.com ), and a file name ( index.html ).

What is a URL path example? ›

A path is the unique, last part of the URL for a specific function or piece of content. For example, for a page whose full URL is http://example.com/node/7, the path is node/7.

What are the three parts of a URL? ›

Parts of a URL. A simple website URL should have at least three components: protocol, domain name, and path.

Where is the path located in a URL? ›

The path specifies the exact location of a page or resource within the website, coming after the domain name and often including multiple segments separated by slashes.

How do I find the full URL path? ›

If you're using JavaScript in the browser you can get the full current URL by using window. location. href .

What is the domain and path of a URL? ›

Domain: a list of the domains of your account. Route: this is how you want to personalize the link to your destination document. The route or also known as “path,” is the part of the URL that comes straight after your domain (i.e., yourdomain.com/PATH)

What is the simple definition of routing? ›

Routing is the process of path selection in any network. A computer network is made of many machines, called nodes, and paths or links that connect those nodes. Communication between two nodes in an interconnected network can take place through many different paths.

Is a URL the same as an address? ›

The web address contains information about the location of the webpage. It is also known as the URL (uniform resource locator). Like the address for your home, a web address organizes information about a webpage's location in a predictable way.

What does URL mean on a bank statement? ›

URL is the abbreviation which means Uniform Resource Locator. It has the link of server where the searches resource is stored.

What does URL mean in networking? ›

A URL (Uniform Resource Locator) is the address of a unique resource on the internet. It is one of the key mechanisms used by browsers to retrieve published resources, such as HTML pages, CSS documents, images, and so on. In theory, each valid URL points to a unique resource.

What is the URL of a network address? ›

A URL (Uniform Resource Locator, also called a web address) is a unique identifier used to locate a resource on the internet. URLs consist of multiple parts -- including a protocol and domain name -- that tell web browsers how and where to retrieve a resource.

What is the link routing? ›

A link-state routing protocol allows routers to map the network by sharing details about the state of their directly connected links. See also: interior gateway protocol, OSPF, IS-IS, routing table.

Top Articles
The Pros And Cons Of Currency Appreciation - FasterCapital
Personal Lines of Credit: What to Know | Capital One
Evil Dead Movies In Order & Timeline
Napa Autocare Locator
Ymca Sammamish Class Schedule
Jonathon Kinchen Net Worth
Beacon Schnider
St Als Elm Clinic
His Lost Lycan Luna Chapter 5
Craigslist Estate Sales Tucson
Cape Cod | P Town beach
Chastity Brainwash
Shariraye Update
Best Restaurants Ventnor
今月のSpotify Japanese Hip Hopベスト作品 -2024/08-|K.EG
Pro Groom Prices – The Pet Centre
Bernie Platt, former Cherry Hill mayor and funeral home magnate, has died at 90
Costco Gas Foster City
Bridge.trihealth
Aris Rachevsky Harvard
Tinker Repo
Mychart Anmed Health Login
Pickswise Review 2024: Is Pickswise a Trusted Tipster?
Pokemon Unbound Shiny Stone Location
Atdhe Net
Lakewood Campground Golf Cart Rental
Air Quality Index Endicott Ny
Www.craigslist.com Austin Tx
Craig Woolard Net Worth
Wonder Film Wiki
How do you get noble pursuit?
Healthy Kaiserpermanente Org Sign On
Greyson Alexander Thorn
R/Orangetheory
Rogold Extension
Devargasfuneral
60 Second Burger Run Unblocked
Capital Hall 6 Base Layout
Diana Lolalytics
拿到绿卡后一亩三分地
Skyrim:Elder Knowledge - The Unofficial Elder Scrolls Pages (UESP)
Mvnt Merchant Services
18 terrible things that happened on Friday the 13th
Anguilla Forum Tripadvisor
Energy Management and Control System Expert (f/m/d) for Battery Storage Systems | StudySmarter - Talents
Nu Carnival Scenes
Mountainstar Mychart Login
The Pretty Kitty Tanglewood
Displacer Cub – 5th Edition SRD
St Als Elm Clinic
Obituary Roger Schaefer Update 2020
Latest Posts
Article information

Author: Trent Wehner

Last Updated:

Views: 6142

Rating: 4.6 / 5 (76 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Trent Wehner

Birthday: 1993-03-14

Address: 872 Kevin Squares, New Codyville, AK 01785-0416

Phone: +18698800304764

Job: Senior Farming Developer

Hobby: Paintball, Calligraphy, Hunting, Flying disc, Lapidary, Rafting, Inline skating

Introduction: My name is Trent Wehner, I am a talented, brainy, zealous, light, funny, gleaming, attractive person who loves writing and wants to share my knowledge and understanding with you.