Routing was first introduced in ASP.NET in .NET 3.5 SP1 and further enhanced in ASP.NET MVC (see Chapter 13). Routing allows you to map a URL to a physical file, which may or may not exist. To implement this functionality in previous versions of ASP.NET, complex hacks or ISAPI filters were needed.
Why use this feature? Well, let's say you are working for an online shop that has a new product being advertised on TV; it is located at the following URL:
www.myshop.com/productDetail.aspx?id=34534
Routing allows you to create a more readable URI mapped through to the page, such as the following:
www.myshop.com/PopularProduct/
URL routing also allows you to create more memorable and search engine–friendly URIs, hiding the internal structure of your application.
Routes are created in the Global.asax file. The following code maps the URL ~/PopularProduct to the page ~/default.aspx?id=34534:
protected void Application_Start(object sender, EventArgs e) { System.Web.Routing.RouteTable.Routes.MapPageRoute( "myPopularRoute", "PopularProduct", "~/default.aspx?id=34534" ); }
Routing has implications for security policies that you may have defined in Web.config, because ASP.NET will check policies for the route rather than the mapped page. To remedy this, MapPageRoute supports an overloaded method that allows you to check that the user has access to the physical file (~/default.aspx?id=34534) as well. Access for defined routes is always checked.
As well as creating simple one-to-one mapping URLs, it is useful to be able to pass in parameters to routes. For example, most shops sell a several types of products, so you could create URLs such as myshop.com/cats or myshop.com/dogs (note selling cats and dogs online is probably a bad idea). To create these type of routes, enclose the value that will change inside curly brackets:
System.Web.Routing.RouteTable.Routes.MapPageRoute( "myProductGroupRoute", "{groups}", "~/default.aspx?id=123" );
Routing parameters can then be retrieved with the following syntax:
string searchTerm=Page.RouteData.Values["group"];
Sometimes it can also be useful to retrieve the URL that will be generated for a specific route to create hyperlinks or redirect the user; this can be done with the GetRouteUrl() method:
Page.GetRouteUrl("myProductGroupRoute", new { group = "brandNew" })
18.218.70.79