ASP.NET 4.0 Routing

Ganeshji
Posted by in ASP.NET category on for Beginner level | Points: 250 | Views : 96156 red flag
Rating: 4.8 out of 5  
 5 vote(s)

In this article, i have tried to explain the ASP.NET 4.0 Routing, with few examples.


 Download source code for ASP.NET 4.0 Routing


Introduction


Using ASP.NET 4.0 routing we can use URLs that do not have to map to specific files in a Web site. As the URL does not have to map to a file, we can use URLs that are descriptive of the user's action and therefore are more easily understood by users.

In an ASP.NET application that does not use routing, an incoming request for a URL typically maps to a physical file that handles the request, such as an .aspx file. For example, a request for
http://mineshoppy/DisplayItem.aspx?ItemId=4 maps to a file that is named DisplayItem.aspx, that contains code and markup for rendering a response to the browser. The Web page uses the query string value of id=4 to determine what type of content to display.

In ASP.NET routing, we can define URL patterns that map to request-handler files,but that do not necessarily include the names of those files in the URL. In addition, we can include placeholders in a URL pattern so that variable data can be passed to the request handler without requiring a query string.


Benefits


In ASP.NET 4.0, URL Routing is fully integrated and much powerful. Hence, one should prefer URL Routing,  over URL Rewriting whenever possible.
  1. It helps a lot in Search Engine Optimization (SEO).
  2. URLs need not have to map to a certain file.
  3. More descriptive/meaningful URLs can be used, which can be easily understandable by users and search engines.
  4. Ease on url rewrite rules.
  5. Using routing, long URL's can be eliminated and file extensions too (like .aspx), can be hidden.
  6. Another advantage of URL routing is that, the physical path/location of web pages residing in the web can be hidden.
For example, the URL for a traditional page that displays items might look like below:
 http:// www.mineshoppy.com/DisplayItem.aspx?ItemId=100

We can now configure the application  using the URL routing engine in ASP.NET 4,  to accept the following URL instead to render the same information:
http://www.mineshoppy.com/DisplayItem/HeadPhone


Route

A URL pattern that is mapped to a handler is called a route. The handler is a physical file, ie., an .aspx file in a Web Form application. We have to create an instance of the Route class by specifying the URL pattern, the handler and optionally a name for the route.   
We can add the route to the application by adding the Route object to the static Routes property of the RouteTable class. The Routes property is a RouteCollection object that stores all the routes for the application.

URL Patterns

A URL pattern can contain literal values and variable placeholders (referred to as URL parameters). The literals and placeholders are located in segments of the URL which are delimited by the slash (/) character.
When a request is made, the URL is parsed into segments and placeholders, and the variable values are provided to the request handler.
In this case variable information is included in the URL and passed to the handler in the form of key-value pairs. For routes, the keys are the placeholder names defined in the URL pattern, and only the values are in the URL.

How to add Routes to Web Form Application

In a Web Forms application, we can create routes by using the MapPageRoute(String, String, String) method of the RouteCollection class. The MapPageRoute method creates a Route object and adds it to the RouteCollection object. We specify properties for the Route object in parameters that we pass to the MapPageRoute method.
          
We add routes in a method that is called from the handler for the Application_Start event in the Global.asax file. This approach makes sure that the routes are available when the application starts.
           First we are registering the Routes in a subroutine and then adding them in the Application_Start() event in the Global.asax file.
         
We need to define the routing in our global.asax file. I have added function for registering routes and called this from the Application_start event handler. We may add any number of routes in the Application_Start event handler.

RouteTable
Stores the URL Routes for an application.

RouteCollection 
Provides a collection of Routes for ASP.NET Routing.

MapPageRoute
MapPageRoute provides a way to define routes for Web Forms applications.
It takes 3 parameters here:
  • string routeName,
  • string routeUrl,
  • string physicalFile

RouteValueDictionary
Represents a case-insensitive collection of key/value pairs that we use in various places in the routing framework, such as when we define the default values for a route or when we generate a URL that is based on a route.

RouteData.Values
Gets a collection of URL parameter values and default values for the route.

Let me now explain all these, using proper examples:

Global.asax




Here, the navigateUrl attribute of the Hyperlink control is set to "~/Items/Laptop".  This is connected to the first route in my global.asax file and the word 'Laptop' is being assigned in the {name} placeholder and is being handled by the Items.aspx page.

URLRouting.aspx


Here i have fetched the value of the {name} in the "Browse-Items" route, using Page.RouteData.Values["name"], and assigned in a Label.





Items.aspx.cs




On executing, UrlRouting.aspx





Output





Setting Default Values for URL Parameters


We can assign a default value for a parameter, while we define a route. The default value is used if a value for that parameter is not included in the URL. We set default values for a route by assigning a dictionary object to the Defaults property of the Route class.
    The following example shows how to add a route that has default values, by using the MapPageRoute(String, String, String, Boolean, RouteValueDictionary) method.

SettingDefaultValues.aspx



Language.aspx




Language.aspx.cs





On Executing, SettingDefaultValues.aspx



Output





When ASP.NET routing handles a URL request, the route definition shown in the example (with default values like, ‘A’ for SectionName and Computer for Paper) produces the results that are listed in the following table.

URL
Parameter Values
/Languages
Paper="Computer" (Default Value)
Section Name="A"  (Default Value)
/Languages/Paper
Paper="Hindi"
Section Name="A" (Default Value)
/Languages/Paper/SectionName
Paper="English"
Section Name="B"


Components of ASP.NET 4.0 URL Routing:

Two main components of ASP.NET URL Routing are:
  • RoutingHandler  
  • Expression Builders
  1.     RouteURLExpressionBuilder
  2.     RouteValueExpressionBuilder

RoutingHandler

Routing is basically a normal HTTPHandler, which is resposible for looking into all the incoming URL request, and look for any Routing definition is available for the URL, if yes then pass the request and data to corresponding resource.

Expression Builders:

Expressions with ASP.NET 4.0  facilitates "Bi-Directional Routing“.

RouteURLExpressionBuilder:  It gives the syntax which results in the URL based on RouteName and Parameter according to the Route Definitions we have.

RouteValueExpressionBuilder: It provides a syntax which receives the value from the RouteName and Parameter from RoutedURL.


How to assess URL Parameters in a routed page?


To access URL parameters by using code


Retrieve the value from the RouteData object and cast it to the appropriate type.
The RouteData object is available in the RouteData property of the Page object. The following example shows how to retrieve a route parameter and convert it to an respective value.

string paper = Convert.ToString(Page.RouteData.Values["Paper"])

The proper picture has been shown above in Language.aspx.cs snap shot.

To access URL parameters by using markup


Create a RouteValue expression that indicates which parameter value that you want to access.
The following example shows a Label that uses a RouteValue expression in its Text property.
<asp:Label ID="Label1" runat="server" Text="<%$RouteValue:name%>" />


WorldPage.aspx





Output :





Generating Routing Friendly URL



We can  generate routing friendly URLs using the Page.GetRouteUrl method. The simplest version of this method takes only 2 parameters.
  • The name of the route and the
  • Values of the parameters.

RoutingFriendly.aspx.cs


Using the GetRouteUrl() method, here we can generate an url.




On Executing RoutingFriendly.aspx



Output

Shows the generated url above the button 'Generate Routing-Friendly URL'.




Bi-Directional Routing


In Bi-Directional Routing, we can:

Decode the Routed URL (RouteValueExpressionBuilder) and
Generate the URL using ASP.NET Routing Mechanism (RouteURLExpressionBuilder).

Decode the Routed URL (RouteValueExpressionBuilder)

We can also access the routes from the url using RouteValue:Name. The snap is already shown above for WorldPage.aspx


Generate the URL using ASP.NET Routing Mechanism (RouteURLExpressionBuilder).


Bidirectional.aspx




On Executing, Bidirectional.aspx




Output





Response.RedirectToRoute()



There is also now a Response.RedirectToRoute() set of methods that we can use to redirect users to a route and optionally pass parameters to it.
          
Response.RedirectToRoute method is a new version of Response.Redirect method. It takes 2 parameters, ie. Name of the route and the parameter value and then redirect to the appropriate, routing-friendly URL.

URLRouting.aspx.cs




On executing, URLRouting.aspx


Click on the Redirect button, and u will be redirected to ...../WebSitehm/Items/pen url.

Output




Difference between URL Routing and URLRewriting 



ASP.NET 4 Routing and ASP.NET URL Rewriting in earlier Frameworks, are  more or less same, in their functionality. The difference only lies in the steps to configure, the syntax in Global.asax and the code-behind pages.
In ASP.NET UrlRewriting, we had to add some markup to Web.config.  These steps are no longer necessary with ASP.NET 4. The routing rules in the Global.asax is shorter, simpler and more readable in ASP.NET 4. The code in the code-behind pages are also simpler.

Example showing, how to generate the url if the URL pattern is  having placeholder with special characters in it.


Type down any text along with special characters in it. According to my example, click on the button. And in the Button_Click event, i have written the code to replace the special characters or spaces with hyphen and underscores respectively.
           The following example is being handled by the 3rd route in my global.asax file. Here the page handler is ShowPage.aspx.


Default2.aspx





On executing , Default2.aspx


After typing in the text box, please click the button and then the hyperlink.




Again in the ShowPage.aspx, i have replaced the hyphen and underscores with special character and spaces respectively to display the correct data in a label.

ShowPage.aspx


Output


After clicking on the hyperlink, you will be navigated here.



Hope this article will be useful for those looking for knowledge on ASP.NET routing. Thanks for reading.


Reference:

http://msdn.microsoft.com/en-us/library/cc668201.aspx




Page copy protected against web site content infringement by Copyscape

About the Author

Ganeshji
Full Name: Zinnia Sarkar
Member Level:
Member Status: Member
Member Since: 7/24/2010 12:50:40 PM
Country: India
Regards, Ganeshji


Login to vote for this post.

Comments or Responses

Posted by: Ermahesh2009 on: 8/23/2011 | Points: 25
Awesome ..very nice effort keep it up .
Posted by: Ganeshji on: 8/24/2011 | Points: 25
Thnx Mahesh! Keep reading!
Posted by: Anweshabhowmick on: 11/22/2011 | Points: 25
Mam it was excellent...............can we do it in VS2008,if possible then How.?Please give some suggestion.
Posted by: Ogipansrk on: 12/14/2011 | Points: 25
Ganeshji,

How to make the first page ....in ur example URLRouting.aspx to URLRouting .....

ogipansrk

Login to post response

Comment using Facebook(Author doesn't get notification)