Dan Maharry

ASP.NET 4.0 Part 12, Routing Helper Functions

by

Welcome to part 12 of my tour through ASP.NET 4.0. In the last episode, we saw how improvements in ASP.NET 4.0 have made it much simpler to get routing for webforms set up and working. In this one, we’ll look in more detail at the new routing-friendly classes, properties and methods you can start to use once routing is set up.

Defining Routes

Let’s start by defining a couple of routes and using them as examples throughout this post.

routes.MapPageRoute("Users", "user-{username}", "~/users.aspx");
routes.MapPageRoute("Forums", "forum-{forumname}", "~/forum.aspx");
routes.MapPageRoute("Threads", "forum-{forumname}/thread-{threadid}", "~/thread.aspx");

We'll also create another one with default values for each of the route parameters, using another of MapPageRoute's overloads.

routes.MapPageRoute("Posts", "post/{forumname}/{threadid}/{postid}", 
"~/thread.aspx", false,
new RouteValueDictionary { 
{ "forumname", "Fishing" }, { "threadid", "12" }, { "postid", "1" } 
});

Should we now visit ~/post/, thread.aspx will load and be passed in "Fishing", "12" and "1" as the values for the forumname, threadid and postid route parameters respectively. Should we visit ~/post/art, the default values for the threadid and postid parameters will passed in along with "art" as the forumname.

MapPageRoute has a couple of other tricks up its sleeve as well. An overload with five parameters allows you to define a basic validation for legal values for each of the route parameters. For example, let's say we wanted forumname to contain only lower-case letters. Then we would define the route like this.

routes.MapPageRoute("Posts", "post/{forumname}/{threadid}/{postid}", 
"~/thread.aspx", false,
new RouteValueDictionary { 
{ "forumname", "Fishing" }, { "threadid", "12" }, { "postid", "1" } 
},
new RouteValueDictionary { { "forumname", "^[a-z]*$" } }
);

Don't forget as well that MapPageRoute is just a quick route to registering a route that is handled by the built-in PageRouteHandler class. If you want to handle the request using your own handler, you can make the equivalent call to routes.Add.

routes.Add("Posts",
new Route("post/{forumname}/{threadid}/{postid}",
new RouteValueDictionary { 
{ "forumname", "Fishing" }, { "threadid", "12" }, { "postid", "1" } },
new RouteValueDictionary { { "forumname", "^[a-z]*$" } }, null,
new PageRouteHandler("~/thread.aspx", false)));

Hyperlinks

With our routes defined, we can now set up hyperlinks between routes. All we need are the name of the route and the values of any route parameters. If we need to do it inline in the code (perhaps because it's part of a databinding operation) we can use the new <%$RouteUrl %> syntax. For example.

Go to <a runat="server" 
href='<%$RouteUrl:RouteName=Users, UserName=Dan  %>'>dan's page</a><br />
Go to <a runat="server" 
href='<%$RouteUrl:RouteName=Forums, ForumName=Coding  %>'>coding forum</a><br />
Go to <a runat="server" 
href='<%$RouteUrl:RouteName=Posts %>'>the default post</a><br />

If we need to set the hyperlink in code-behind, it's easiest to use GetRouteUrl(), a new method on System.Web.UI.Control and therefore the Page class. (This actually calls RouteCollection.GetVirtualPath() to get the required URL if you'd prefer to use that instead).

GetRouteUrl() has four overloads, broadly taking the following form

GetRouteUrl([string routeName], routeParameters);

Where specifying the routeName is optional and the routeParameters can be added as either an object of anonymous type or as a RouteValueDictionary. For example,

// Named route, parameters in anonymous type object
hypUsers.NavigateUrl = Page.GetRouteUrl("users", new {username = "Dan" });
// Named route, parameters in RouteValueDictionary
hypForums.NavigateUrl = Page.GetRouteUrl("forums", 
new RouteValueDictionary { { "forumname", "Fishing" } );
// Named route, no parameters set, so defaults used
hypPosts.NavigateUrl = Page.GetRouteUrl("posts", new {} );
// No route named
hypNoName.NavigateUrl = Page.GetRouteUrl(new { forumname = "Gaming" });

In the last example here, we've not named a route to use a basis for a URL, but we have specified a route parameter called forumname, which appears in three of our declared routes. Which route will it use as a basis to generate the URL? Simply, the first route defined that contains the named parameter. In this case, that's "forums".

Redirection

If you need to redirect a user's browser to a given address, you'll need to call one of the three new redirect methods we mentioned briefly in part 10: either Response.RedirectToRoute() or Response.RedirectToRoutePermanent(). Both have the same five overloads with the only difference that RedirectToRoute() sends an HTTP 302 temporary redirect to the browser and RedirectToRoutePermanent() sends a HTTP 301.

// No Route Named, Parameters In Anonymous Type object
Response.RedirectToRoute( new { username = "Dan" });
// No Route Named, Parameters In RouteValueDictionary
Response.RedirectToRoute( 
new RouteValueDictionary { { "forumname", "Fishing" } ););
// Only route named, so default parameter values used
Response.RedirectToRoute("posts"); 
// Named route, parameters in anonymous type object
Response.RedirectToRoute("users", new {username = "Dan" });
// Named route, parameters in RouteValueDictionary
Response.RedirectToRoute("forums", 
new RouteValueDictionary { { "forumname", "Fishing" } );

Note that both these methods are equivalent to calling Response.Redirect(url, stopProcessing) with stopProcessing set to false. Again, more on that here in part 10.

RouteParameters

Last but not least, DataSource users will be interested to know that Microsoft have added a new RouteParameter object to ASP.NET 4.0 which you can use in exactly the same way as, for instance, a QueryStringParameter or a ControlParameter. If you use the Configure DataSource wizard you'll see it added to the bottom of the Source list when you need to add a WHERE clause to the data source.

1_RouteParameter

If you do select Route from the Source list, you'll need to set the name of the route parameter you want to use and also give a default value for the parameter if it isn't available for some reason.

2_RouteParameter

These are the only differences between using a RouteParameter and any other parameter object you use with your DataSources. If you prefer to write the code yourself, the net result of the screesnshots above is the following markup.

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:UsersDB %>" 
SelectCommand="SELECT [UserId], [Username] FROM [Users] WHERE ([Username] = @Username)">
<SelectParameters>
<asp:RouteParameter DefaultValue="Dan" Name="Username" RouteKey="username" 
Type="String" />
</SelectParameters>
</asp:SqlDataSource>

So then, in this article, we've looked at the new methods and objects you'll likely use most often when working with webforms and routing. Until the next time, happy coding.

ASP.NET 4.0 Part 11, Configuring Routing Is Easier

by

Welcome to part 11 of my tour through ASP.NET 4.0. In this episode, we're going to take a look at how routing for webforms has been made easier to set up in ASP.NET 4.0. This will be followed up in Part 12 with a look at the new route-aware classes, methods and properties in more detail.

Routing was originally introduced in ASP.NET 3.5 SP1 as part of the foundations to enable the ASP.NET MVC template engine to work. It could also be used against the webforms engine but a certain amount of rolling-your-own-foundation coding was required to enable it properly.

In ASP.NET 4.0, that initial legwork is no longer necessary as routing for webforms is now supported as standard in System.Web, the majority of the configuration for routing is pre-set in system-wide config files, and some extra goodness has been added into various classes for ease of use as well. All in all, if you haven't had occasion to try routing with webforms before, try it with ASP.NET 4.0. It's really simple.

Why?

There are a metric / boatload / of articles introducing routing and how it works. In a nutshell, routing, like URL rewriting, is a response to two general criticisms of websites.

  1. We humans prefer it if a page's URL is readable. For example, http://myforums.info/forum-Music is easier to read than http://myforums.info/forum.aspx?id=2. It's easier to remember too
  2. Search engines prefer human-readable URLs as well. In particular, they like URLs with no querystring parameters at the end. And, the more search engine friendly a site's URLs are, the better indexed they may be by a search engine and the higher they may appear in search rankings. (Obviously, URLs aren't the only thing indexing robots look at when they come to your site - Descriptions and Keywords are up there with a host of other things too - but they certainly help.)

So then, the major consequence of routing as far as webforms is concerned are URLs which are more readable for humans and search robots alike with no reduction of information to the page itself.

How?

Routes are initialized as named, regular expressions (using a subset of the standard .NET RegEx syntax) and given an order in which they will be matched against the currently requested URL. For example,

  1. user-{username}
  2. forum-{forumname}
  3. forum-{forumname}/thread-{threadid}

Let's say a request comes to the server for http://myforums.info/forum-Music.

  • If the request is for a page that actually exists on the site, no routing actually occurs and that page is loaded and runs as normal.
  • If the page doesn't exist, the requested URL is matched against each initialized route in the order you've specified. In this example, user-{username} doesn't match the requested URL, so the next route is tried.
  • When a route matching the requested URL is found, the request is routed to the page that deals with that route. Any named sections of the route are then made available to the handling page within the RouteData collection. For example, http://myforums.info/forum-Music matches forum-{forumname}, so control for the request would be passed to the page for that route along with a RouteData collection containing one KeyValuePair where forumname is the Key and Music is its value.
  • If no route is found to match the incoming request, it is passed to the standard ASP.NET 404 page or a custom page if you've defined one.

Routing Is Neither URL Rewriting nor Redirection

Hopefully, the above description should differentiate routing from URL rewriting and page redirection. However, just in case it didn't...

  • Routing is not Page Redirection
    Redirection can only work if the incoming URL is for a page that exist. It works by sending a response to the browser saying that the page has moved with the browser then issuing a second request for the URL it is being redirected to. Routed URLs on the other hand do not necessarily refer to a page that actually exists - they will often seem to refer to directories for example - and are dealt with in one request. Browsers will not issue a second request for the actual page which handles the route.
  • Routing is not URL Rewriting
    URL rewriting occurs very early on in the asp.net request pipeline, literally as request processing is beginning. When the rewritten URL is resolved, IIS then sends it down the pipeline to find a handler to deal with it. It has no control over what handler deals with the request. Routing, on the other hand, occurs further down the pipeline, once the request has been authorised, at which point the routing module dispatches the request to a handler based on which route the request matches and the handler specified by you to deal with the route. (IIS team member Ruslan Yarushev goes into much more detail on the differences between the two in this article.)

Setting Up Webforms Routing In ASP.NET 3.5

Briefly, here are the steps needed to enable routing for webforms in ASP.NET 3.5.

  1. All routing classes and namespaces are found in a new DLL, System.Web.Routing.dll to be included as a reference in your website.
  2. The UrlRoutingModule needs to be added to the list of modules enabled for the site in web.config (as described here in MSDN)
  3. A handler class inheriting IRouteHandler needs to be created that understands how to resolve the route into the page or handler that will actually process the request and generate the RouteData collection. Both Phil Haack and Chris Cavanagh put forward basic implementations of this handler, discussing potential security issues.
  4. Register the routes for the site in the Application_Start handler of global.asax using your new route handler class. For example,
protected void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
public static void RegisterRoutes(RouteCollection routes)
{
// Route existing files (default will shortcut routing if physical file exists)
RouteTable.Routes.RouteExistingFiles = true;
// Add StopRoutingHandler for .axd and .asmx requests
routes.Add(new Route("{resource}.axd/{*pathInfo}", 
new StopRoutingHandler()));
routes.Add(new Route("{service}.asmx/{*pathInfo}", 
new StopRoutingHandler()));
// Add existing routes
routes.Add("Users", new Route("user-{username}", 
new WebFormRouteHandler("~/users.aspx", true)));
routes.Add("Forums", new Route("forum-{forumname}", 
new WebFormRouteHandler("~/forum.aspx", true)));
routes.Add("Threads", new Route("forum-{forumname}/thread-{threadid}", 
new WebFormRouteHandler("~/thread.aspx", true)));
// Add an unnamed handler for all unknown requests (now created in the PageRoute table)
//routes.Add(new Route("{value}", 
new WebFormRouteHandler("~/pages/default.aspx")));
}
  1. Write your pages as you would normally using the RouteData collection in place of the Querystring class. You'll need to make RouteData available by passing a RequestContext object to the object that needs access to the RouteData. Again, Phil Haack suggests one way of doing this (via an IRoutableObject interface) here.
  2. Finally, you have to configure IIS to have ASP.NET deal with requests to your routes, thus passing them on to your RouteHandler classes. If you're using IIS6 and your routes are extension-less (i.e. missing .aspx, .asmx , .ashx etc file extensions in their composition), you'll need to configure wildcard maps on a per-directory level according to where your routes point else you'll end up serving all your static files with ASP.NET as well. Full instructions for this come courtesy of Steve Sanderson (Part 1, Part 2).

Setting Up Webforms Routing In ASP.NET 4.0

By comparison, the procedure is far more straightforward in ASP.NET 4.0, thanks in large part to Microsoft being able to open up and edit System.Web and the classes inside it. Let's compare

  1. System.Web.Routing has been folded into System.Web.dll in .NET 4.0 so there is no need for an additional reference to it in your solution.
  2. The UrlRoutingModule is also already set up in the machine-wide web.config file which means that it works straight off the bat in IIS 6. For IIS 7 users, however, you'll need to enable it with the following addition to web.config.
<?xml version="1.0"?>
<configuration>
...
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
...
</modules>
</system.webServer>
</configuration>
  1. ASP.NET 4.0 includes an implementation of IRouteHandler for you to use - it's called PageRouteHandler. There's no reason why you can't build your own as before, but it's no longer necessary.
  2. You still need to register routes for your application but if you're using the built-in PageRouteHandler class, you can use the MapPageRoute helper method to make route registration clearer.
protected void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
public static void RegisterRoutes(RouteCollection routes)
{
// Route existing files (default will shortcut routing if physical file exists)
RouteTable.Routes.RouteExistingFiles = true;
// Add StopRoutingHandler for .axd and .asmx requests
routes.Add(new Route("{resource}.axd/{*pathInfo}", 
new StopRoutingHandler()));
routes.Add(new Route("{service}.asmx/{*pathInfo}", 
new StopRoutingHandler()));
// Add existing routes with MapPageRoute helper method
routes.MapPageRoute("Users", "user-{username}", "~/users.aspx");
routes.MapPageRoute("Forums", "forum-{forumname}", "~/forum.aspx", true);
// MapPageRoute is equivalent to adding a Route with the PageRouteHandler like so
routes.Add("Threads", new Route("forum-{forumname}/thread-{threadid}", 
new PageRouteHandler("~/thread.aspx", true)));
}
  1. Any pages you write now automatically have access to the RouteData collection as a property of the Page class itself, as well as several other route-aware additions we'll review in the next section.
protected void Page_Load(object sender, EventArgs e)
{
lblHello.Text = 
RouteData.Values["username"] == null ?
"Hello Mr A. Nonymous" : 
String.Format("Hello {0}", RouteData.Values["username"].ToString());
}
  1. Regrettably, while integration into IIS7 Integrated Mode remains quite simple, you still need to configure IIS6 \ IIS7 in Classic mode to associate the routes used in your site with ASP.NET as you did in ASP.NET 3.5. That's a failing of IIS6 rather than ASP.NET.

As you can see, setting up routing for an ASP.NET 4.0 webforms site is somewhat simpler than for the previous version as Microsoft has taken the opportunity to refactor routing into the core ASP.NET framework. In the next episode, we'll look at several of the new route-aware features for use once in ASP.NET 4.0 sites we've set routing up. Until then, happy coding!