After disassembling and trying to understand Scott Mitchell's example of url routing in asp.net 3.5 with web forms, I've come up with a very simple sample in
vb.net, which is my favourite language. Basically, in the class file containing the routehandler which has been registered in Global.asax, the parameter is first grabbed from the route data values of the RequestContext:
Code:
Dim categoryName As String = requestContext.RouteData.Values("CategoryName")
Then it's added to the items in the current httpcontext:
Code:
Dim catName As String = categoryName
System.Web.HttpContext.Current.Items("Category") = catName
Return CType(BuildManager.CreateInstanceFromVirtualPath("~/CategoryProducts.aspx", GetType(Page)), Page)
In the page that needs to grab the parameter from the url in order to display the right item, just grab the value of the item in the items collection of the current httpContext object, normally you'd have used a Request.QueryString to retrieve this value:
Code:
Dim category As String = HttpContext.Current.Items("Category")
The Url is dynamically reconstructed by using a Helpers class with a method such as this:
Code:
Public Shared Function FormatCategoryUrl(ByVal categoryName As String) As String
Dim strVirtualPathData As VirtualPathData
Dim params As RouteValueDictionary
params = New RouteValueDictionary(New With {.categoryName = categoryName})
strVirtualPathData = RouteTable.Routes.GetVirtualPath(Nothing, "View Category", params)
Return strVirtualPathData.VirtualPath
End Function
For example, in the hyperlink that leads to the products by category page, its NavigateUrl property will be something like:
Code:
<asp:HyperLink ID="hlGoToCategory" runat="server"
NavigateUrl='<%# Helpers.FormatCategoryUrl(Eval("CategoryName").ToString()) %>'
Text='<%#Eval("CategoryName") %>'></asp:HyperLink>
I understand that things might get a bit more complicated by adding authentication and authorization for example, but I just needed an extremely simple application so that I could grasp the basic workings of the url routing mechanism. Also, I'm aware that the all thing has been simplified in .Net 4.