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.
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
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.
Now if you put 2 in url it will print information about customer 2.
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
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.
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.
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.
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.
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.
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.
Now if you put 2 in url it will print information about customer 2.
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
good post, it really very helpful for me...thanx..
ReplyDeleteportable wireless router
when I do postback lose routing, help please.
ReplyDelete@Erick Munoz Salinas Can you send me your source code? Did you register routes in global.asax?
ReplyDeletesystem.web routing is not showing in asp.net 3.5
ReplyDeleteGive me one simple example using database using ASP.NET?
ReplyDeletehelp me?
Yes still doesn't work...
ReplyDeleteRoutData.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
@5f5e98714407426c94a4e861e88ac842:disqus Sure in future I will post something for that
ReplyDeleteIts only available from asp.net 4.0
ReplyDelete@0ebcd8103b8e9ca67e8e7e5db8d74d72:disqus - Please send me code
ReplyDeleteit is throwing error as object reference not set to an instance of an object in string line of customer.aspx.cs page
ReplyDeleteGetting Object Reference not set error when trying to retrieve the querystring using Page.RouteData.Values[].ToString() on customer page.
ReplyDeletewhich framework you are using It works only on .net 4.0 or higher versions
ReplyDeletewhich framework you are using? I think you are using lower version of .net
ReplyDeleteI 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.
ReplyDeleteThanks Jalpesh! for your interest.
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.
ReplyDeleteYes it supported in asp.net 4.0. Can you send me your code to see whats wrong with that.
ReplyDeleteIt shows NullExceptionerror. I Checked & verify that i used 4.0 version. Upload new code.. following is my code :
ReplyDeletevoid 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));
small correction.. In Application_Start write
ReplyDeleteRouteConfig.RegisterRoutes(RouteTable.Routes);
instead of RegisterRoutes(RouteTable.Routes);
This will work in Framework 4.5, 100% sure
thanks
ReplyDeleteit tried many times but can't get out of this error "Object reference not set to an instance of an object."
ReplyDeletei am using .net framework 4.0
here are the screen shot of my Customer.aspx.cs and Global.asax pages.
You are not passing Id for that. Can you provide me your code for that.
ReplyDeletewell i thought the same but i don't know where to pass the id
ReplyDeleteSir does this app require IIS ?
ReplyDeletei am getting error "Object reference not set to an instance of an object"
Nope it does not require IIS. Which .Net version you are using?
Deletewhere to provide id?
ReplyDeleteIts already mentioned in article itself
Deleteits coming error.where to provide Id plz say me
ReplyDeletefirst you need to register your route like following in register route function
DeleterouteCollection.MapPageRoute("RouteForCustomer", "Customer/{Id}", "~/Customer.aspx");
and you can get that via following.
string id = Page.RouteData.Values["Id"].ToString();
can't work Error..Object reference not set to an instance of an object. how to solve this problem
Deletewhich .net framework you are using? I think you are using older framework before .net framework 4.0
DeleteIt doesn't work on postback
ReplyDeleteWhat error you are getting?
Delete