ASP.net 4.0: URL Routing

June 1, 2010 by C#   ASP.NET  

URL routing allow developers to decouple/map/rewrite urls into a more readable/descriptive format, also quite handy when you're busy with migration, SEO etc.
Also see Rudimentary url rewriting

Microsoft introduced routing (.net 3.5 SP1) into its codebase primarily for use with their MVC framework. In ASP.net 4.0 however Microsoft extended support to Web Forms as well.
It is also possible to implement routing within Web Forms using .net 3.5 SP1, which we will discuss in the next post.

Lets have a quick look at the ASP.net 4.0 Web Forms implementation:

1. In your Application_Start event (within Global.asax), we're going to call a method named MapPageRoutes and pass the global routing table to the method:

void Application_Start(object sender, EventArgs e)
{
    MapPageRoutes(RouteTable.Routes);
}

2. Within the RegisterRoutes method (which you need to create in your Global.asax) use the MapPageRoute method located on the RouteCollection (routes) instance e.g.
void RegisterRoutes(RouteCollection routes)
{
    routes.MapPageRoute("testroute", "tester/{id}", "~/test.aspx", false,
        new RouteValueDictionary { { "id", "1" } }, 		// default value
        new RouteValueDictionary { { "id", @"^\d+$" } }); 	// constraint e.g. only numerals            
}

Which essentially means http://somehost/test.aspx?id=1 becomes http://somehost/tester/1

The MapPageRoute method has 4 overloads (excl the overloaded method):
public Route MapPageRoute(string routeName, string routeUrl, string physicalFile);
public Route MapPageRoute(string routeName, string routeUrl, string physicalFile, bool checkPhysicalUrlAccess);
public Route MapPageRoute(string routeName, string routeUrl, string physicalFile, bool checkPhysicalUrlAccess, RouteValueDictionary defaults);
public Route MapPageRoute(string routeName, string routeUrl, string physicalFile, bool checkPhysicalUrlAccess, RouteValueDictionary defaults, RouteValueDictionary constraints);
public Route MapPageRoute(string routeName, string routeUrl, string physicalFile, bool checkPhysicalUrlAccess, RouteValueDictionary defaults, RouteValueDictionary constraints, RouteValueDictionary dataTokens);

  • routeName : Name of the route
  • routeUrl : Url pattern for the route
  • physicalFile : Physical url for the route
  • checkPhysicalUrlAccess : Prevents or permits ASP.net to check if the user has rights the the physical url. (Roles)
  • defaults : Default values for the parameters
  • constraints : Constraints on parameters passed to the route (Regex based)
  • dataTokens : Extra values passed to the physical page (not used for routing)

Note:

If you want to capture all values passed to the url and not just the specified pattern, this can be achieved by using an asterisk e.g.
routes.MapPageRoute("testroute", "tester/{id}/{*somename}"...

3. In the physical file (e.g. test.aspx) the route points to, we can access our routing data via the RouteData property:
protected void Page_Load(object sender, EventArgs e)
{
    Response.Write(RouteData.Values["id"]);
}

In order to output mapped urls in the markup of our pages, we can simply hard-code urls (hmmmm) or alternatively we can make use of RouteUrl expressions e.g.
<asp:HyperLink runat="server" ID="HyperLink1" NavigateUrl="<%$RouteUrl:id=20 %>" Text="test">
</asp:HyperLink>

To access the values passed to our route within markup:
<asp:Label runat="server" ID="Label1" Text="<%$RouteValue:id%>" />

In order to redirect to a mapped page, Microsoft added the RedirectToRoute method to the Response class e.g.
Response.RedirectToRoute("tester", new { id = 20 });

Its also possible to get the mapped url from the GetRouteUrl method (added to the Page class):
Page.GetRouteUrl("tester", new { id = 20 });

In conclusion I feel this is quite nifty functionality - even though its been around for quite a while (been using similar functionality on my PHP projects for many years (RewriteEngine)).


Leave a Comment


need help January 17, 2012 by abdulghaffar

I'm a beginner and i want to change all my links in my web application by replace ( xxxxx.aspx ) with ( xxxxx.html ) in all the the web application and this is the code i have in mind but i don't know where to start or how? void RegisterRoutes(RouteCollection routes) { routes.MapPageRoute("RootPages", "{file}.html", "~/{file}.aspx"); } void Application_Start(object sender, EventArgs e) { // Code that runs on application startup RegisterRoutes(RouteTable.Routes); } i will be thankful if tell me where to start or how to solve my problem and useful links to read best regard abdulghaffar