Sunday, December 11, 2011

Easy URL routing in ASP.NET 4.0 web forms

In this post I am going to explain URL routing in greater details. This post will contain basic of URL routing and will explain how we can do URL routing in fewer lines of code.

Why we need URL routing ?

Let’s consider a simpler scenario we want to display a customer details on a ASP.NET Page so how our page will know that for which customer we need to display details? The simplest way of doing is to use query string we will pass a customer id which uniquely identifies customer in  query string. So our url will look like this.
Customer.aspx?Id=1
This will work but the problem with above URL is that its not user friendly and search engine friendly. who is going to remember that what query string parameter I am going to pass and why we need that parameter. Also when search engine will crawl this site it will going to read this URL blindly as this url is not informative because it query string is not readable for search engine crawlers. So your search engine will be ranked lower as this URL is not readable to search engine crawlers.Now when do a URL routing our URL will be cleaner shorter and simpler like this.
Customers/Id/1/
Here anybody in world can understand it talking about customer and this page will used to show customer details.Even search engine crawler will also know that you are talking about customers. That is why we need URL routing.

URL routing and ASP.NET

In earlier versions of ASP.NET we have to write lots of code for URL routing but Now with ASP.NET 4.0 you can easily route in fewer lines of code.

So let’s start a Demo where I will demonstrate you how we can easily route URLs. So let’s first create a ASP. NET web form application via File->New->Project and a dialog box will open just like below and then created a empty project called URL rewriting.

Add new project for URL rewriting in asp.net 4.0

After creating a project I have added global.asax – where we are going to write url mapping logic and then I have added an asp.net page called which will display customer information just like below.

Project for URL rewriting in asp.net 4.0

So everything is now ready let’s start writing code. First thing we need to do is to define routes. Route will map a URL to physical page.First I will create static function called Register route which map route to particular file and then I am going to call this from application_start event of global.asax. Following is code for that.

using System;
using System.Web.Routing;

namespace UrlRewriting
{
public class Global : System.Web.HttpApplication
{

protected void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}

public static void RegisterRoutes(RouteCollection routeCollection)
{
routeCollection.MapPageRoute("RouteForCustomer", "Customer/{Id}", "~/Customer.aspx");
}

}
}


Now as mapping code has been done let’s right code for customer.aspx page. I have have following code in page_load event of customer.aspx

using System;

namespace UrlRewriting
{
public partial class Customer : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string id = Page.RouteData.Values["Id"].ToString();

Response.Write("<h1>Customer Details page</h1>");
Response.Write(string.Format("Displaying information for customer : {0}",id));

}
}
}


Here in above code you can see that I am getting value from page route data and then just printing it. In real world it will fetch customer data from database and show customer details on page.

Now let’s run that application. It will print a details of customer as I have passed Id in URL suppose you pass 1 as id in URL then it will look like following.

Customer details via URL rewriting in asp.net 4.0

Now if you put 2 in url it will print information about customer 2.

Customer two details via URL rewriting in asp.net 4.0

That’s it. So we have enabled URL routing in asp.net in fewer lines of code. In next post I am going to explain redirection with URL routing.

Hope you like this post. Stay tuned for more.. Till then Happy programming

Share:

32 comments:

  1. good post, it really very helpful for me...thanx..


    portable wireless router

    ReplyDelete
  2. when I do postback lose routing, help please.

    ReplyDelete
  3. @Erick Munoz Salinas Can you send me your source code? Did you register routes in global.asax?

    ReplyDelete
  4. system.web routing is not showing in asp.net 3.5

    ReplyDelete
  5. Give me one simple example using database using ASP.NET?
    help me?

    ReplyDelete
  6. Yes still doesn't work...

    RoutData.values is nothing.

    Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
    ' Code that runs on application startup
    RouteTable.Routes.MapPageRoute("RouteForCustomer", "Customer/{id}", "~/Customer.aspx")
    End Sub

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load

    'RouteTable.Routes.MapPageRoute("RouteForCustomer", "Customer/{id}", "~/Customer.aspx")
    If Request.QueryString("id") IsNot Nothing Then
    Try
    RouteTable.Routes.MapPageRoute("RouteForCustomer", "Customer/{id}", "~/Customer.aspx")
    Catch ex As Exception

    End Try

    Dim id As String = Page.RouteData.Values("Id").ToString()

    Response.Write("Customer Details page")
    Response.Write(String.Format("Displaying information for customer : {0}", id))

    End If

    End Sub

    ReplyDelete
  7. @5f5e98714407426c94a4e861e88ac842:disqus Sure in future I will post something for that

    ReplyDelete
  8. @0ebcd8103b8e9ca67e8e7e5db8d74d72:disqus - Please send me code

    ReplyDelete
  9. it is throwing error as object reference not set to an instance of an object in string line of customer.aspx.cs page

    ReplyDelete
  10. Getting Object Reference not set error when trying to retrieve the querystring using Page.RouteData.Values[].ToString() on customer page.

    ReplyDelete
  11. which framework you are using It works only on .net 4.0 or higher versions

    ReplyDelete
  12. which framework you are using? I think you are using lower version of .net

    ReplyDelete
  13. I am using 4.0 FW only. But still I could'nt make it possible. whether URL rewriting is possible or not in .NET 4.0? please reply with code sample which exactly suits and works fine.
    Thanks Jalpesh! for your interest.

    ReplyDelete
  14. ya its working but can you give me an example for URL rewriting to be done while at the time of the page gets loaded itself.

    ReplyDelete
  15. Yes it supported in asp.net 4.0. Can you send me your code to see whats wrong with that.

    ReplyDelete
  16. It shows NullExceptionerror. I Checked & verify that i used 4.0 version. Upload new code.. following is my code :

    void Application_Start(object sender, EventArgs e)
    {
    // Code that runs on application startup
    RegisterRoutes(System.Web.Routing.RouteTable.Routes);
    }

    public static void RegisterRoutes(System.Web.Routing.RouteCollection routeCollection)
    {
    routeCollection.MapPageRoute("RouteForCustomer", "Customer/{Id}", "~/Customer.aspx");
    }

    string id = Page.RouteData.Values["Id"].ToString();

    Response.Write("Customer Details page");
    Response.Write(string.Format("Displaying information for customer : {0}", id));

    ReplyDelete
  17. small correction.. In Application_Start write

    RouteConfig.RegisterRoutes(RouteTable.Routes);



    instead of RegisterRoutes(RouteTable.Routes);


    This will work in Framework 4.5, 100% sure

    ReplyDelete
  18. it tried many times but can't get out of this error "Object reference not set to an instance of an object."

    i am using .net framework 4.0
    here are the screen shot of my Customer.aspx.cs and Global.asax pages.

    ReplyDelete
  19. You are not passing Id for that. Can you provide me your code for that.

    ReplyDelete
  20. well i thought the same but i don't know where to pass the id

    ReplyDelete
  21. Sir does this app require IIS ?
    i am getting error "Object reference not set to an instance of an object"

    ReplyDelete
    Replies
    1. Nope it does not require IIS. Which .Net version you are using?

      Delete
  22. its coming error.where to provide Id plz say me

    ReplyDelete
    Replies
    1. first you need to register your route like following in register route function

      routeCollection.MapPageRoute("RouteForCustomer", "Customer/{Id}", "~/Customer.aspx");

      and you can get that via following.

      string id = Page.RouteData.Values["Id"].ToString();

      Delete
    2. can't work Error..Object reference not set to an instance of an object. how to solve this problem

      Delete
    3. which .net framework you are using? I think you are using older framework before .net framework 4.0

      Delete
  23. It doesn't work on postback

    ReplyDelete

Your feedback is very important to me. Please provide your feedback via putting comments.

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews