Click here to Skip to main content
Click here to Skip to main content

URL Routing with ASP.NET 4.0

By , 29 Apr 2010
 

Table of Contents

Introduction

One thing that has always pinched me is the long URLs that I used to see in several of my projects. Due to better manageability, I used to have several folders, i.e. folder hierarchy for maintainability of my application. But the thing that I didn't ever like was the full physical path of pages in URLs. There are other ways which allow us to get rid of it like URL rewriting, but I didn't like that.

We could also have our own custom URL route handler or some third party solution, but they have never been strong enough for an application.

Frankly speaking, one of my clients asked me several times, "Why does this .aspx extension displays in the URL" and also told me that he does not like these long URLs. I used to tell him, this is the normal behavior of ASP.NET application. But we can change it with our own custom solution. However, that will require a little bit of time and also require a lot of testing.

But when Microsoft released ASP.NET MVC 2 with .NET Framework 3.5 SP1, and provided this Routing feature with it, I was very happy and started exploring it. In the meantime, I thought that it should also be provided with ASP.NET, because every time you may not require to follow MVC architecture and also found that MVC has nothing special to do with URL Routing. So I was expecting and waiting for ASP.NET Webform Routing.

Now Microsoft introduced URL Routing with ASP.NET 4.0. URL routing is fully integrated, very powerful and straightforward.

Prerequisite

  • Visual Studio 2010

What is URL Routing

We access our webapplication using some URL that is normally the physical path of the pages. So URL Routing is a way to provide our own URL in lieu of the physical path of the page. One other way, Routing allows us a way to configure our application to accept a requested URL which actually doesn't map to physical files. From the security perspective of the application, it's important because one can easily know the solution structure of the application.

URL Routing Processing

Fig 1.0: URL Routing Processing

Why URL Routing

In 1999, on usability Jakob Nielson wrote on his blog "URL as UI" 6 essential points about URL. These are:

  • A domain name that is easy to remember and easy to spell
  • Short URLs
  • Easy to type URLs
  • URLs that visualize site structure
  • URLs that are "hackable" to allow users to move to higher levels of the information architecture by hacking off the end of the URL
  • Persistent URLs that don't change

As from all these points, we can see the URLs as a part of user interface and it should be simple and easy. URLs should also made us visualize the structure of our application which might be a security concern for us, etc.

ASP.NET 4.0 provides us the features, taking care of all the points mentioned above.

Also, these URLs helps in SEO (Search engine optimization) and improve the page hits but put in the appropriate keywords.

URL Routing Earlier

Earlier, URL routing was not so easy. For that, we require to have our own custom handler in a way that whenever a URL is requested, our custom route handler class should be invoked, and forward the request to the appropriate requested page or we could have some third party solution. So let's say if we are going to develop our own custom handler, then what do we need to do.

  1. We define the mapping in Global.asax, which maps a route pattern to route handler class.
  2. We require to develop a Route handler class which actually receives the URL, parses it, stores any route parameters into some location that should be accessible to the requested page and returns the instance of requested page or forwards the request to the HTTPhandler that handles the requested route.
  3. Writing code in the target page in the way so that it can fetch the route parameters and renders the page accordingly.

So you can imagine that it was not a straightforward task. It also requires some considerable amount of effort to develop it.

URL Routing with ASP.NET 4.0

As I already discussed in my introduction section, that ASP.NET 4.0 provides us a simplified and robust way to handle the entire URL routing mechanism. To provide URL routing, ASP.NET is now equipped with myriad classes and a number of methods to provide this feature, which allows to easily decouple the URL with physical files. We just need to use them.

ASP.NET 4.0 URL Routing Flow

Fig 2.0: ASP.NET 4.0 URL Routing Flow

ASP.NET 4.0 router enables to define any kind of custom routes and we can easily map it to our webform page.

ASP.NET 4.0 also made our life simpler by providing us the feature "Bi- Directional routing" with the help of several components like Route Table, Page Routehandler and ExpressionBuilders.

What is Bi-directional Routing

With the help of the Route table, we can not only decode the Routed URL with the Route table and with the help of other methods provided by the ASP.NET 4.0, we also generate the URL with the ASP.NET routing mechanism, which gives us the opportunity, not to hard code the URL at several places, rather it will be dynamically generating the URLs with the help of Routing Definition.

So we just require to change the Route Table on any changes in the URL, and don't need to change it in several other places throughout the solution.

Bi-directional Routing

Fig 3.0: Bi-directional Routing

Components of ASP.NET 4.0 URL Routing

There are two main components of ASP.NET 4.0 URL Routing.

RoutingHandler

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

Expression Builders

Expressions are provided with ASP.NET 4.0 to facilitate Bi-Directional Routing and more. Basically there are two types of ExpressionBuilders.

  1. RouteURLExpressionBuilder: As the name suggests, it provides the syntax which results in the value, i.e., URL based on RouteName and Parameter according to the Route definitions we have.
  2. RouteValueExpressionBuilder: As above, it generates the URL, RouteValueExpressionBuilder provides a syntax which receives the value from the RouteName and Parameter from RoutedURL.

There are also a few new properties HttpRequest.RequestContext and Page.RouteData which facilitate the availability of the parameters to all resources.

An Example

In this example, I will be displaying the image and name of the book on my web page.

Here, I will be going to an ASP.NET application and will take you step by step to create the application.

Note:

  • I have used VS2010 Beta 2 version for this sample.
  • We have to use the namespace System.Web.Routing in our application to access Routing specific classes and methods.

Step 1

Define the Route in Application_Start of Global.asax. Also include namespace System.Web.Routing.

void Application_Start(object sender, EventArgs e)
{
    // Code that runs on application startup
    RouteTable.Routes.MapPageRoute("StoreRoute",
    "BookStore/{Name}",
    "~/Webpages/BookStore/ViewBookDemo.aspx");
}  

Step 2

  1. Now in ViewBookDemo.aspx, I have four links. In the first two, I have hardcoded the URL and in the last, I used RoutURLExpressionBuilder to generate the URL dynamically. That is known as Bi- Directional routing. This is the one I also liked the most, in several cases, we have had links in our pages that were generally hard coded.

    img7.gif

  2. I also have a Label in the page and I set the Text property dynamically with the help of Routing information as above.

Step 3

Here, I fetch the parameter from the Routing Table and set the Image1 URL dynamically.(Include namespace System.Web.Routing):

    //fetching the parameter that is Route table
    string name = Page.RouteData.Values["Name"] as string;
    if (name != null)
    {
        if (name == "CSS")
        {
            Image1.ImageUrl = "~/images/css.jpg";
        }
        else if (name == "Django")
        {
            Image1.ImageUrl = "~/images/django.jpg";
        }
        else if (name == "IPhone")
        {
            Image1.ImageUrl = "~/images/iphone.jpg";
        }
        else if (name == "Linq")
        {
            Image1.ImageUrl = "~/images/Linq.jpg";
        }
    }         
}

To view the entire code, please download the attachment.

Now my solution hierarchy in the demo application is:

Solution Explorer

Fig 4.0: Solution Explorer

And according to it, my URL should be http://localhost:2039/Webpages/BookStore/ViewBome.aspx?Name=CSS as:

Demo Application

Fig 5.0: Demo Application

Now when a user requests this application, the request is processed as:

i4.JPG

Fig 6.0: Request Processing

Feedback and Suggestions

Feedback is the key for me. I would request all of you to share your feedback and give me some suggestions, which would encourage and help me in writing more articles.

References

History

  • 29th April, 2010: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Brij
Software Developer (Senior)
India India
Member
Brij is a Microsoft MVP in ASP.NET/IIS Category and a passionate .NET developer. Having around 5 years of experience in IT field, currently serving a MNC as a Sr. developer.
 
He is a very passionate .NET developer and have expertise over Web technologies like ASP.NET 2.0/3.5/4.0, jQuery, JSON, Javascript, IIS and related technologies. He is also a Exchange Server (EWS) Specialist. He has great experience in design patterns and N-Tier Architecture.
 
He is also certified as Microsoft Certified Technologies Specialist-ASP.NET and Microsoft Certified Technologies Specialist-WCF in .NET 4.0. He has also received several awards at various forums and his various articles got listed as "Article of the day" at ASP.NET Microsoft Official Website www.asp.net.
 
He has done MCA from NIT Durgapur and completed his graduation from Lucknow University.
 
Learning new technologies and sharing knowledge excites him most. Blogging, solving problems at various forums, helping people, keeps him busy entire day.


Visit his Blog: Brij's arena of .NET
 
Area of Expertise :
C#, ASP.NET 2.0,3.5,4.0, AJAX, JQuery, JSON, XML, XSLT, ADO.Net, WCF, Active Directory, Exchange Server 2007 (EWS), Java script, Web Services ,Win services, DotnetNuke, WSS 3.0,Sharepoint Designer, SQL Server 2000/2005/2008

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionrediect to login.aspxmemberplazzasele30 Mar '13 - 7:06 
Hi..
first of all, thank you for your article. it is nice to have people like you to help beginners like me.
 
now my question is: i have an application, In the masterpage.master.cs I am checking the user session, if the session = null. i want to redirect the user to a login.aspx file, the url will be like this: mydomain.com/login.aspx
what i want is to have the url   like this mydomain.com/login
is it possible..? i have tried some ways with no luck..
 
can you please provide some code.
 
the code: Global.asax
void LogInRoutes(RouteCollection routes)
      {
            routes.MapPageRoute(
            "login",   //Name of the Route (can be anyuthting)
            "login/", // URL with parameters
            "~/login.aspx"); //Page which will handles and process the request
      }
      void Application_Start(object sender, EventArgs e)
      {
            // Code that runs on application startup
            LogInRoutes(RouteTable.Routes);
      }
masterpage.master.cs
Response.RedirectToRoute("login","login");
Response.End();
GeneralMy vote of 5memberFaithcz27 Mar '13 - 11:37 
Nice article. I didn't know a thing about routing, until now.
QuestionThanksmemberMember 327776026 Feb '13 - 7:45 
Very good article. Thanks.
patel

GeneralMy vote of 4memberveenusethi17 Feb '13 - 23:49 
Thanks for explaining very clearly routing concept
GeneralMy vote of 5membersandeepkumarvemula11 Feb '13 - 21:49 
thanks Smile | :)
GeneralMy vote of 5mvpadriancs15 Jan '13 - 21:16 
cool, thanks
GeneralMy vote of 5memberSavalia Manoj M8 Nov '12 - 16:34 
good
GeneralRe: My vote of 5memberNAVNEET KUMAR SINGH3 Dec '12 - 16:05 
you u r the greate sir ur answer is so helpful
GeneralMy vote of 5memberhsuhsutin30 Sep '12 - 19:48 
Good Article
QuestionHow to route to www.myDomainName/MemberIdmembermustafeena13 Sep '12 - 10:44 
I have a table memberid, membername . How to display the Membername in the index.aspx page
 
Some help would be appreciated. coz am struck in this.
 
Thanks
mustafeena
Check this out

QuestionTrackingmemberPatrick Harris18 Aug '12 - 19:37 
How do you track routing? For instance, I have two url's that route to the same page, how do I track traffic going through each url?
GeneralMy vote of 5memberAlluvialDeposit16 Jul '12 - 22:42 
nice article ! Smile | :)
GeneralMy vote of 5memberBernd Dulat11 Jul '12 - 0:16 
Excellent explanation, simple example.
Questionwhether to use rewrting or routingmemberjpchoudhari18 Jun '12 - 4:34 
hi,
 
I am developing a website where I am giving user s option to add pages dynamically and to specify SEO friendly URLs which are not physically present.
My concern is if I am using routing I will.have to dynamically add new routing information per page added. how I can achieve this??
GeneralMy vote of 5memberims.sanjay16 May '12 - 20:57 
Very Helpful Sir.
Thanks a lot
GeneralMy vote of 5memberMonjurul Habib27 Apr '12 - 22:26 
nicely done Smile | :)
Generalmy vote of 4memberUday P.Singh6 Feb '12 - 18:08 
good job!
GeneralRe: my vote of 4mentorBrij7 Feb '12 - 4:46 
Thanks
Cheers!!
Brij
Microsoft MVP ASP.NET/IIS
Visit my Blog: http://brijbhushan.net

GeneralMy vote of 5memberCS14016 Feb '12 - 18:06 
thank u.
GeneralMy vote of 5memberShameel14 Dec '11 - 22:26 
Very well written article.
GeneralRe: My vote of 5mvpBrij15 Dec '11 - 5:53 
Thanks Shameel!!
Cheers!!
Brij
Microsoft MVP ASP.NET/IIS
Visit my Blog: http://brijbhushan.net

QuestionCode does not work! [modified]memberMember 5178181 Dec '11 - 8:38 
I downloaded your code
Opened the solution file with Visual Studio 2010 Service Pack 1
Hit the Debug button and
OMG | :OMG:
received this error:
 
Server Error in '/' Application.
--------------------------------------------------------------------------------
 
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
 
Requested URL: /Webpages/BookStore/CSS
 

WTF??!!!! Now I have to debug your sh*t along with the rest of the work I have to do? Your mis-spelling of 'Route' as 'Rout' is also terribly distracting!!

modified 1 Dec '11 - 14:53.

AnswerRe: Code does not work!mvpBrij1 Dec '11 - 8:58 
Man
 
First I strongly disliked that you have not used the the words that should never be used in forums.
 
Member 517818 wrote:
Now I have to debug your sh*t along with the rest of the work I have to do?

 
You don't need to debug at all if it's not working. Just need to put a message below the article.
 
No one ever reported that code does not work in last 1.5 years ( Since I posted It.
 
I just downloaded the code after more than a year and it's working like a charm.I am also using VS 2010 SP1
 
One thing you can try set the Default.aspx as Start Page.
 
Again want to reiterate that use the decent words at forums.
 
Also I welcome your first message at CodeProject
 
God bless you
Cheers!!
Brij
Microsoft MVP ASP.NET/IIS
Visit my Blog: http://brijbhushan.net

AnswerRe: Code does not work!membermark merrens14 Dec '11 - 21:39 
Member 517818 wrote:
WTF??!!!! Now I have to debug your sh*t along with the rest of the work I have to do? Your mis-spelling of 'Route' as 'Rout' is also terribly distracting!!

 
How very ignorant and rude of you. If you can't figure out how to use an article's code send the author a POLITE note requesting help. Telling him that his work is 'sh*t' is not the way to get a response. If you don't like it, don't use it. Clearly, you are far too busy and important to bother with anything that other people do. I suggest you are probably far too lofty to need to spend any time at CP: try another site that will put up with your childish outbursts. Mad | :mad:
"If you think it's expensive to hire a professional to do the job, wait until you hire an amateur." Red Adair.
nils illegitimus carborundum
 
me, me, me

AnswerRe: Code does not work!memberAndy_L_J14 Dec '11 - 22:09 
I see no contribution by you to this site for 8 years and then you post this? ...*ss Hat
I don't speak Idiot - please talk slowly and clearly
 
'This space for rent'
 
Driven to the arms of Heineken by the wife

AnswerMy vote of 1.mentorKeith Barrow14 Dec '11 - 22:19 
Member 517818 wrote:
I downloaded your code
Opened the solution file with Visual Studio 2010
Service Pack 1
Hit the Debug button and
OMG | :OMG:
received this
error:
 
Server Error in '/'
Application.
--------------------------------------------------------------------------------
 
The
resource cannot be found.
Description: HTTP 404. The resource you are
looking for (or one of its dependencies) could have been removed, had its name
changed, or is temporarily unavailable. Please review the following URL and make
sure that it is spelled correctly.
 
Requested URL:
/Webpages/BookStore/CSS

You downloaded it, alongside 1,324 other people, yet you are the only one to experience the error. Though by no means certain, I'd suggest it is you that is having the problem.
 

Member 517818 wrote:
WTF??!!!! Now I have to debug your sh*t along with the rest of the work I have to do?

Wow, that's quite a mouth, especially for someone who hasn't contributed anything useful to the site. What did you pay? Nothing? As you are such a red-hot dev I suggest you work this out for yourself, though I also suspect you are incapable of doing this.
 

Member 517818 wrote:
'Rout' is also terribly distracting!!

And there we have it, the last recourse of the dull witted. Having nothing intelligent to say, have a go at the other person's spelling and grammar. I'm sure you'd have excelled at an arts education, especially social studies.
 

One thing I would like to thank you for, pointing me at a useful and well-written article.

AnswerRe: Code does not work!memberShameel14 Dec '11 - 22:24 
If you cannot handle a simple error like the one you pointed out, then you're in the wrong business.
 
Member 517818 wrote:
WTF??!!!! Now I have to debug your sh*t along with the rest of the work I have to do?

No, you don't have to. Nobody is forcing you to download code and debug it. Now if you have a need to use the code, then send a polite message to the author asking for help.
AnswerRe: Code does not work!mvpCPallini14 Dec '11 - 22:29 
Member 517818 wrote:
WTF??!!!! Now I have to debug your sh*t along with the rest of the work I have to do?

Big Grin | :-D
You made my day.
Your employer has all my symphaty, sincerely.
If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler.
-- Alfonso the Wise, 13th Century King of Castile.

This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong.
-- Iain Clarke

[My articles]

GeneralNice ArticlememberHaider Mehndi Rizvi18 Dec '10 - 9:13 
Nice Article on URL Routing.
 
Check this Article on URL Routing.
 
URL Routing in ASP.Net
GeneralRe: Nice ArticlementorBrij18 Dec '10 - 19:37 
Thanks Haider!!!
 
I saw your post. It's equally good. Keep posting!!
Best of luck Smile | :)

Questionhow url routing in asp.net 2.0membermadhgari.rk14 Oct '10 - 23:20 
hi brij,
ur article is very good, but my requirement in asp.net 2.0, in 2.0 there is no name space system.web.routing.
plz let me know url routing in asp.net 2.0
 

 

Thanks in advance,
Rama krishna
AnswerRe: how url routing in asp.net 2.0mentorBrij15 Oct '10 - 8:35 
Hi Rama,
 
I already discussed in my Article, that Routing feature got introduced in ASP.NET 4.0 only. So in ASP.NET 2.0 you wont find any support for this.
 
If you want to implement change the URL , you have to go for for URL writing or you may have to buy some third party dll.
 
Better you go for URL Writing, here you can chamge the URL according to your need. For details of URL rewriting,
Have a look

QuestionHow to make Subdomain routing?memberPradeep Babu Yadagani24 Sep '10 - 6:42 
Hi,
 
Thank you for very useful notes. It all talks about the Url routing related to query string. But I need routing related to subdomains. Here are the details.
 
I am using .NET 4.0, IIS7, ASP.NET 4.0. I have an web application hosted as "mycompany.com". I have some clients, say client1, register at my site. I want to give him a
 
URL like http://client1.mycompany.com. Similarly for client2 URL will be http://client2.mycompany.com
 
http://mycompay.com has provision to allow new clients to register at my site. Any new client should able to view his area by using URL http://clientN.mycompany.com.
 
This is very similar to Microsoft's spaces.live.com; Each individual having hotmail/live ID can access his spaces. Ex: http://ypradeep23.spaces.live.com
 
Is it achievable using URL routing?
Can you please guide me in design this solution. Thank you inadvance.
 
Regards,
Pradeep.
AnswerRe: How to make Subdomain routing?mentorBrij25 Sep '10 - 1:53 
I have not tried this. In ASP.NET MVC, we can do this easily.
 
Have a look
 
There are also ways at the IIS level to do URL rewriting such that you map multiple host header domains to one physical site/application which I think would allow you to achieve what you are after as well
Cheers!!
Brij
My Blog:http://brijbhushan.wordpress.com

Check my latest Article :ViewState - Various ways to reduce performance overhead

GeneralMy vote of 3memberamittrivedimca21 Sep '10 - 2:50 
Useful Information.
GeneralRe: My vote of 3mentorBrij25 Sep '10 - 1:54 
Thanks Dude!!
Cheers!!
Brij
My Blog:http://brijbhushan.wordpress.com

Check my latest Article :ViewState - Various ways to reduce performance overhead

GeneralMy vote of 5membersantosh poojari30 Jun '10 - 21:18 
Too Good
GeneralRe: My vote of 5mentorBrij1 Jul '10 - 2:55 
Thanks Santosh Smile | :)

GeneralMy vote of 5memberachuki128 Jun '10 - 19:16 
Well explained and very useful article.
GeneralRe: My vote of 5mentorBrij29 Jun '10 - 0:01 
Thanks buddy for appreciation.Glad to know that you liked it.

GeneralNice one!mentorSandeep Mewara1 May '10 - 8:45 
Good work... Thumbs Up | :thumbsup:
GeneralRe: Nice one!mentorBrij1 May '10 - 9:45 
Thanks Sandeep!!
Glad you like it Smile | :)

GeneralGood Work BrijmvpAbhijit Jana30 Apr '10 - 22:30 
Nice Work !!! Thumbs Up | :thumbsup:
Cheers !
Abhijit Jana | MVP
Web Site : abhijitjana.net
Don't forget to click "Good Answer" on the post(s) that helped you.

GeneralRe: Good Work BrijmentorBrij1 May '10 - 5:23 
Nice to see your comments.
Thanks Smile | :)

GeneralNice onememberPetr Pechovic30 Apr '10 - 6:15 
5 from me Wink | ;)
 
Petr
GeneralRe: Nice onementorBrij30 Apr '10 - 6:24 
Thanks a lot Petr. Have a nice weekend Smile | :)

GeneralRe: Nice onememberluisnike1930 Apr '10 - 13:40 
5 for me too... Thumbs Up | :thumbsup:
luisnike19

GeneralRe: Nice onementorBrij30 Apr '10 - 17:14 
Thanks dude!!

GeneralWell explainedmembersrinandan..29 Apr '10 - 20:04 
Hi,
Gud article about url routing which will be very help for the SEO.
I would like to give 5 of 5 as you have explained very well with the screen-shots. really you have gud writting skill Smile | :)
 
Keep it up.
 
Regards,
Sri...
GeneralRe: Well explainedmentorBrij30 Apr '10 - 5:11 
Thanks a lot for your support.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 29 Apr 2010
Article Copyright 2010 by Brij
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid