Monday, July 25, 2011

URL Routing in ASP.Net 4.0 (Simple) example / tutorial

In ASP.Net 3.5 SP1 Microsoft made it possible to perform URL Routing / Rewriting natively in the Framework.  In ASP.Net 4.0, they made it even simpler.  To get started you will need to make sure you have several things in place to include Visual Studio 2010, IIS7, and (of course) ASP.Net 4.0 Framework.
When we say routing, we mean to take a URL and make it a safe SEO friendly URL.  For instance, turn:
Into:
http://www.someserver.com/somepage/somevalue/
This has been made extremely easy in ASP.Net 4.0 with a few simple steps.


The Setup:
Create a new .Net 4.0 website in VS2010.  Choose ASP.NET Web Site (I typically code in Visual Basic, so choose that as your template).  The Development Environment will create several items in your solution explorer.  The most interesting in this context is the Global.asax file. 


The Global.asax file:
In order to enable routing, we need to tell the Framework what we want to route and how we expect to format it. So we create a new Sub called RegisterRoutes (This is the acceptable industry standard name for the Sub).


Note: You will need to make a reference to the System.Web.Routing namespace in your solution.  To do this, right-click your solution name | click Add Reference | and scroll to System.Web.Routing
Then you will need to add an import to your Global.asax file, like so:
<%@ Application Language="VB" %>
<%@ Import Namespace="System.Web.Routing" %>




At the bottom of your Global.asax file add the following right before the </script>  tag.
Shared Sub RegisterRoutes(ByVal routes As RouteCollection)
        routes.MapPageRoute("View",
            "{q}",
            "~/Chad.aspx")
When we break this down, we are adding a MapPageRoute item to the RouteCollection.  The method accepts (or expects) three values (all Strings):
(“View”,”{q}”,”~/Chad.aspx”)
“View” is our name for this route.  This is how we will refer to this route in our subsequent pages.
“{q}” is the name for our query string.  For instance if our querystring was products we would name this “{products}”.
“~/Chad.aspx” is the page that we are routing TO.
Obviously, if your application expected to more routes, you would add more routes.MapPageRoutes to your RegisterRoutes method.
Additionally, to support more than one querystring per route, You would simply define it in the second value of the MapPageRoutes method:
For a single querystring we have:
“{querystring}”
To have multiple querystrings we would use:
“{querystring1}/{querystring2}”


Now we need to add a trigger.  Since this route will be applicable to the entire site and we want it to load immediately on the start of the application, we simply call our new method in the Application_Start method:
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
        RegisterRoutes(RouteTable.Routes)
    End Sub
I believe it is pretty self-explanatory what we are accomplishing here.
Now that our route is setup, let’s see how we initiate and then read the querystring on the subsequent page.


Originating Page:
So in our route called View, we have one querystring we need to populate and the route has a defined page that it knows to go to.
When we are ready (in this example we are using a button click) we will call the method Response.RedirectToRoute.
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Response.RedirectToRoute("View", New With {.q = “QuerystringValue”})
    End Sub


Here we are using the method RedirectToRoute by calling our route name (View) and then populating our querystring named q.  If you recall from our route mapping in the Global.asax file, we setup to route to the Chad.aspx page.  So if we were to look at our raw URL, it would look like:
However, thanks to our mapped routing, it will now look like:


So how do we read the value on our recipient page?  Let’s take a look.


Recipient Page:
To look at the querystring value, you will want to parse out the URL and look for the querystring you just passed in.  Thankfully, Microsoft thought of this and you aren’t actually parsing out the URL, you are really looking through the RouteCollection collection.
This being the case, you will need a trigger (in this case we are using page_load of the Chad.aspx page that we referenced in the Global.asax file).
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim QString As String = Page.RouteData.Values("q").ToString
    End Sub
So here, we are dimensioning the variable QString as a String and then instantiating it with the value from Page.RouteData.Value(“q”).ToString().  Of course we named our querystring value “q” and thus, QString will be populated with our querystring value.  We now can use the querystring in processing data or whatever means we need to.


Happy .Netting.  Saleh

2 comments:

  1. i really interesting with this ASP.NET, i know that latest version for ASP.NET is ASP.NET 5, is this tutorial can work in ASP.NET 5 ?

    ReplyDelete
  2. Routing was introduced in the 3.0 framework. This particular example will work as it uses the integrated method. Microsoft likes to pick up on trends and will integrate those into their framework, thus making it easier to accomplish popular tasks. Older versions required you to make handlers and modules to accomplish routing.
    If you happen to get stuck on something, send me an email and we'll see if a second set of eyes can help. 8^)

    ReplyDelete