Using URL Routing with Web Forms

Words
911
Reading
5 min
Listen
Play
9y

What Will I Learn?

How to URL Routing with ASP.NET Web Forms.

Requirements

ASP.NET Core

Difficulty

Intermediate

Tutorial Contents

  • URL Routing
  • Mapping Routes
  • Registering Routes in Global.asax
  • Handling a Routed Request
  • City.aspx

Using URL Routing with Web Forms

ASP.NET Web Forms support URL routing. For example, a page that shows information for US cities could look something like this:

http://www.domain.com/City.aspx?id=chicago

This is not a very clean URL. Users without a good understanding of the web might wonder what some of those characters are for. And search engines can't easily tell which keywords are important from looking at the URL. In addition, there might even be cases where you don't really want the user to know exactly what file is being served or the tools you used to create it. (ASPX files are obviously created using ASP.NET.) A newer URL might look something like this:

http://www.domain.com/Cities/chicago

This URL is much cleaner and also SEO-friendly (meaning that it is easier for search engines to index appropriate keywords for this page). And there is no indication of exactly what file is being served or what tools were used to create it.

In MVC, all URLs tend to look something like this because of the way content is served. However, as of Service Pack for the Microsoft .NET Framework, you can easily implement URLs like this with ASP.NET Web Forms as well.

URL Routing

One way to think of URL routing is as a different way to specify query arguments. Of course, it works differently than query arguments, but the routing path does indeed specify arguments.

For instance, in the example URLs above, the "chicago" portion of the URL specifies the city to display. You could have a single page that displayed information for any city based on the value at this position. This value could be a primary key in a database or something else that your page can use to locate the required information.

To implement URL routing, you specify a virtual path with a number of placeholders. You can then map that virtual path to one of your physical pages. When your page is loaded, it can query ASP.NET to obtain the values in each of those placeholders.

Mapping Routes

You should map your routes when your web application starts. The easiest way to do that is by adding code to the Application_Start() handler in Global.asax as shown in Listing 1. This code calls the RegisterRoutes() method, which I created to map all my routes.

RegisterRoutes() calls RouteCollection.MapPageRoute() to register each route. The first argument is the name of the route. The value of this argument is not important unless you have code that needs to look up a route by name.

The second argument to RouteCollection.MapPageRoute() is the virtual path described earlier. Placeholders are specified using curly braces ({}). The name of the placeholder (the name between the curly braces) is the name used to identify the corresponding placeholder.

Note that a virtual path of just {id} would not work. With this virtual path, any single-level directory would map to this route. For example, www.domain.com/default.aspx, www.domain.com/states, etc. would all map to this route. Each route must have a unique virtual path or else one of the routes will get mapped to the wrong page. (Besides, I think the addition of "/Cities/" to the virtual path makes the entire path clearer, and more SEO-friendly.)

Finally, the last argument specifies the physical page that this route should be mapped to. This is the page that will be loaded when a URL matching this route is requested. This argument must begin with ~/. Note that the page doesn't need to exist in the Cities folder. In fact, normally, the Cities folder would not even exist.

You can define as many routes as you need to.

Listing 1: Registering Routes in Global.asax

<%@ Application Language="C#" %>
<%@ Import Namespace="System.Web.Routing" %>
<script runat="server">
    void Application_Start(object sender, EventArgs e) 
    {
        // Code that runs on application startup
        RegisterRoutes(RouteTable.Routes);
    }
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.MapPageRoute("City", "Cities/{id}", "~/City.aspx");
    }
</script>

Handling a Routed Request

The next step is to implement the page that handles the routed request. In this case, City.aspx. Listing 2 shows this page's Load event handler.

If this is not a postback, the code starts by obtaining the value in the id placeholder. It does this by querying the RouteData.Values collection. Note that you should include some reasonable error handling with this code. It is possible for the user to request the page directly, in which case there would be no routing data.

If the id value is found, the code then attempts to lookup the data that corresponds to the value. In this case, it looks it up in a List collection. A more common scenario would be one where the code looks the value up in a database.

Finally, if the item is found, the corresponding data is displayed in the page. Otherwise, a message that states the City is not available is displayed. Alternatively, you could redirect the user to your home page or an error page if the placeholder data was missing or invalid.

Listing 2: City.aspx

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        CityInfo city = null;
        object id = String.Empty;
        // Attempt to get City ID from routing data
        if (RouteData.Values.TryGetValue("id", out id))
        {
            city = Cities.CityList.Find(c => c.ID == id.ToString());
        }
        if (city != null)
        {
            // We found the requested city
            lblName.Text = city.Name;
            lblPopulation.Text = city.Population.ToString("#,##0");
        }
        else
        {
            // The requested city was not found
            lblName.Text = "City is not available!";
        }
    }
}

The result is a Web Form that works much like any other Web Form, except it has a virtual URL as shown in Figure 1.

Figure 1: A Web Form with a Virtual URL

And that's really all there is to it. Of course, you'll need to ensure any links to your routed pages use the virtual path. Ideally, your users will never see a link to the physical page that handles routed URLs.



Posted on Utopian.io - Rewarding Open Source Contributors

Using URL Routing with Web Forms | Ecency