Routing in ASP.Net 4.0 Web Forms

In this blog post I would like to talk about a new ASP.Net 4.0 feature, URL Routing. I know this issue has been explained from various people on the web but I will give my own example.

We could implement routing since ASP.Net 3.5 SP1 but it was there primarily to support ASP.Net MVC. Even in that release you could implement rounting in web forms but it was a quite difficult thing to do.

However in ASP.Net 4.0 there is an integrated support for routing. It becomes easy to map requests in your site onto pages in your application.

This is made possible with the introduction of the handler PageRouteHandler that is responsible for dispatching routes onto pages. There is also the MapPageRoute function of the RouteCollection collection that defines a route handled by a page.

Our main goal when designing and implementing web sites is to make them highly discoverable by the search engines. In other words to make them SEO friendly. ASP.Net focuses on SEO and provides us with many SEO oriented features.

Have a look in this post of mine for more SEO features in ASP.Net 4.0.It makes no sense to have an e-commerce website or a website that you place you cv and noone is able to discover this page.

I will demonstrate routing by providing a step by step example using VS 2010 Ultimate edition, C# 4.0 and ASP.Net 4.0.

1) Launch Visual Studio 2010 as Administrator (express edition will work fine). Create a new empty website and choose a suitable name for it. Choose C# as the development language.Choose as Web location ,HTTP and the whole URL should look something like http://localhost/MyRoute

2) Add two web forms to your application. You can leave the first one with the default.aspx name and name the second Products.aspx. Write some sample content on each page e.g "This is the home page", "This is the products page".

3) Build and run your application. You will see the Default.aspx page loading. Then type this in the browser window , http://localhost/MyRoute/Products.aspx and see the Products page loading. Well this is a typical web forms functionality where we basically navigate through to the physical file.

4) Now let's try use routing. Add a new item in your application, a Global Application Class , Global.asax.

5) In the Application_Start event handling routine type:

 void Application_Start(object sender, EventArgs e) 
        // Code that runs on application startup



6) Now we should make some changes in our web.config file.We must instruct IIS to map all requests through the managed modules that are installed. Open your web.config file and type:

    <modules runAllManagedModulesForAllRequests="true">


7) Run your application again and type



Congratulations, you have successfully used routing in ASP.Net 4.0.Please note that the original URLs are still valid,



Hope it helps!!!



1 Comment

Comments have been disabled for this content.