ASP.net 2.0 (.net 3.5 SP1): URL Routing
In the previous post we had a quick look at
the routing functionality in ASP.net 4.0.
essentially means (for example) http://somehost/test.aspx?id=1 becomes http://somehost/tester/1
Routing was originally added via .net 3.5 SP1 for use with the Microsoft MVC framework,
but with regards to Web Forms, Microsoft only added some real support in ASP.net 4.0.
It is however possible adding your own support for routing within ASP.net 2.0 & .net 3.5 SP1, lets have a quick
look on how to achieve this.
Step 1: Add a reference to the System.Web.Routing assembly to your project.
Step 2: Make sure that you've got the required entries in your configuration file (e.g. web.config)
<system.web> <httpModules> ... <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> </httpModules> </system.web> ... <system.webServer> <modules> ... <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </modules> <handlers> ... <add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/> </handlers> </system.webServer> ...
Step 3: Next we're going to add some extension methods - which provides the same methods available within ASP.net 4.0.
RouteCollectionExtensions.cs
using System; using System.Web.Routing; public static class RouteCollectionExtensions { public static Route MapPageRoute(this RouteCollection route, string routeName, string routeUrl, string physicalFile) { return MapPageRoute(route, routeName, routeUrl, physicalFile, null, null, null); } public static Route MapPageRoute(this RouteCollection route, string routeName, string routeUrl, string physicalFile, RouteValueDictionary defaults) { return MapPageRoute(route, routeName, routeUrl, physicalFile, defaults, null, null); } public static Route MapPageRoute(this RouteCollection route, string routeName, string routeUrl, string physicalFile, RouteValueDictionary defaults, RouteValueDictionary constraints) { return MapPageRoute(route, routeName, routeUrl, physicalFile, defaults, constraints, null); } public static Route MapPageRoute(this RouteCollection route, string routeName, string routeUrl, string physicalFile, RouteValueDictionary defaults, RouteValueDictionary constraints, RouteValueDictionary dataTokens) { if (routeUrl == null) { throw new ArgumentNullException("routeUrl"); } Route item = new Route(routeUrl, defaults, constraints, dataTokens, new RouteHandler(physicalFile)); route.Add(routeName, item); return item; } }
We also need to define a handler for handling the request.
RouteHandler.cs
using System.Web; using System.Web.Routing; using System.Web.UI; using System.Web.Compilation; public class RouteHandler : IRouteHandler { private string _physicalFile; public RouteHandler(string physicalFile) { _physicalFile = physicalFile; } public IHttpHandler GetHttpHandler(RequestContext requestContext) { HttpContext.Current.Items["RouteData"] = requestContext.RouteData; return BuildManager.CreateInstanceFromVirtualPath(_physicalFile, typeof(Page)) as Page; } }
Step 4: Next we need to add the routes to the global.asax.
void RegisterRoutes(RouteCollection routes) { routes.MapPageRoute("testroute", "tester/{id}", "~/test.aspx", new RouteValueDictionary { { "id", "1" } }, // default value new RouteValueDictionary { { "id", @"^\d+$" } }); // constraint e.g. only numerals } void Application_Start(object sender, EventArgs e) { RegisterRoutes(RouteTable.Routes); }
Within the page we're routing to, we access the routing data like this:
public System.Web.Routing.RouteData RouteData { get { return HttpContext.Current.Items["RouteData"] as System.Web.Routing.RouteData; } } protected void Page_Load(object sender, EventArgs e) { Response.Write(RouteData.Values["id"]); }
Date - 2010-06-06 21:23:46
Comments - 0
ASP.net 4.0: URL Routing
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)).
Date - 2010-06-01 13:22:55
Comments - 0
First 1 2 3 4 5 6 7 8 9 10 Last / 42 Pages (83 Entries)