Url Routing in Asp.Net Web Forms


One of the coolest features in Asp.Net 3.5  SP1 is web form URL  Routing (thanks for asp.net team). URL routing would really help in Search Engine based websites. You can download the article source code from the bottom of the page

How to Implement URL Routing

1) Create a web site using VS 2008 C#.
2) Right click the project and add reference to System.Web.Routing dll (make sure you have Asp.Net 3.5 Service Pack 1 installed in your machine)
3) Add the following lines to web.config file

Web.conifg  Configuration

The application resides in IIS 6.0 and IIS 7.0 you should  add the UrlRoutingModule class to the httpModules

<httpModules>
<add name=”UrlRoutingModule” type=”System.Web.Routing.UrlRoutingModule,System.Web.Routing,Version=3.5.0.0,Culture=neutral,PublicKeyToken=31BF3856AD364E35″ />
</httpModules>

For IIS 7.0 only

<system.webServer>
<modules>
<remove name=”UrlRoutingModule” />
<add name=”UrlRoutingModule” type=”System.Web.Routing.UrlRoutingModule,System.Web.Routing,Version=3.5.0.0,Culture=neutral,PublicKeyToken=31BF3856AD364E35″ />
</modules>
<handlers>
<add name=”UrlRoutingHandler” preCondition=”integratedMode” verb=”*” path=”UrlRouting.axd” type=”System.Web.HttpForbiddenHandler, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a” />
</handlers>
</system.webServer>

Global.asax file Configuration

Add Import directive to Import System.Web.Routing name space

<%@ Import Namespace=”System.Web.Routing” %>

Register Routes in Application_Start method

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

public static void RegisterRoutes(RouteCollection routes)
{
routes.Add(“MemberList”, new Route
(
“member/{name}”,
new MemberRouteHandler(“~/member/userlist.aspx”)
));
}

The first parameter member/{name} which denote the url structure, here the url which starts /member/{name} (ex : /member/deepu/) will point physically to the following path ~/member/userlist.aspx

The above RegisterRoutes method register a class called MemberRouteHandler.cs

using System.Web.Compilation;
using System.Web.UI;
using System.Web;
using System.Web.Routing;

public interface IRoutablePage
{
RequestContext RequestContext { set; }
}

public class MemberRouteHandler : IRouteHandler
{
public MemberRouteHandler(string virtualPath)
{
this.VirtualPath = virtualPath;
}

public string VirtualPath { get; private set; }

public IHttpHandler GetHttpHandler(RequestContext
requestContext)
{
var page = BuildManager.CreateInstanceFromVirtualPath
(VirtualPath, typeof(Page)) as IHttpHandler;

if (page != null)
{
var routablePage = page as IRoutablePage;

if (routablePage != null) routablePage.RequestContext = requestContext;
}

return page;
}

}

Now we can create the Aspx pages to test the Routing. We need to create two aspx files member listing file and detail file.

Create a folder called member in root of the site.  (you can keep any name but make sure you have to change in global.asx file in Route constructor “member/{name}”)

Create a aspx page inside the member folder called default.aspx

This page will have a list of Members in Tabular format. I am going to use asp.net List view control to achieve this.

<form id=”form1″ runat=”server”>

<asp:ListView ID=”lvUserList” runat=”server”>
<LayoutTemplate>
<table width=”50%” style=”background-color: lightgrey;” cellpadding=”2″ cellspacing=”1″
border=”0″>
<tr style=”background-color: white”>
<td width=”100″ align=”center”>
Member ID
</td>
<td align=”center”>
Name
</td>
<td width=”75″ align=”center”>
Age
</td>
<td width=”50″>
</td>
</tr>
<asp:PlaceHolder ID=”itemPlaceholder” runat=”server” />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr style=”background-color: white”>
<td align=”center”>
<asp:Label ID=”lab” Text='<%# DataBinder.Eval(Container.DataItem, “MemberID”)%>’
runat=”server” />
</td>
<td>
<asp:Label ID=”Label1″ Text='<%# DataBinder.Eval(Container.DataItem, “Name”)%>’ runat=”server” />
</td>
<td align=”center”>
<asp:Label ID=”Label2″ Text='<%# DataBinder.Eval(Container.DataItem, “Age”)%>’ runat=”server” />
</td>
<td align=”center”>
<a href=”<%= ResolveUrl(“~/member/”)%><%# DataBinder.Eval(Container.DataItem, “Name”)%>”>
Detail</a>
</td>
</tr>
</ItemTemplate>
<ItemSeparatorTemplate>
<br />
</ItemSeparatorTemplate>
</asp:ListView>
</form>

Above markup will have a list of members and the hyper link column you can see the url structure which is defined in gloabal.asax file RouteMethod pattern.

<a href=”<%= ResolveUrl(“~/member/”)%><%# DataBinder.Eval(Container.DataItem, “Name”)%>”>

ResolveUrl(“~/member/”) = point to member folder from the root
<%# DataBinder.Eval(Container.DataItem, “Name”)%> = second parameter Member Name.  [for ex: ResolveUrl(“~/member/deepu”) ]

Default.aspx.cs code behind

using System;
using System.Collections.Generic;
using System.Linq;

public partial class Memeber
{
public int MemberID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindUsers();
}
}

void BindUsers()
{

var items = new List<Memeber>()
{
new Memeber {MemberID = 1,Name = “Arjun”, Age = 1},
new Memeber {MemberID = 2,Name = “Deepu”, Age = 29},
new Memeber {MemberID = 3,Name = “Rakesh”, Age = 31},
new Memeber {MemberID = 4,Name = “Abhilash”, Age = 21},
};

lvUserList.DataSource = items.ToList();
lvUserList.DataBind();
}

We have completed the listing page. The next page will be the detail page which will be rendering the member name from the URL routing.

userlist.aspx page Markup

<form id=”form1″ runat=”server”>
<div>
<asp:Label ID=”labMemberName” runat=”server” />
</div>
</form>

In the code behind file for the detail page you must implement IRoutablePage interface class.

Code behind :

public partial class user_userlist : System.Web.UI.Page, IRoutablePage
{
public System.Web.Routing.RequestContext requestContext;

#region IRoutablePage Members
public System.Web.Routing.RequestContext RequestContext
{
set { requestContext = value; }
}
#endregion
protected object RouteValue(string key)
{
if (requestContext != null && requestContext.RouteData != null)
{
return requestContext.RouteData.Values[key];
}
return null;
}

protected void Page_Load(object sender, EventArgs e)
{
object memberName = RouteValue(“name”);
if (memberName != null)
{
labMemberName.Text = memberName.ToString();
}
}
}

Note : If you are implementing url routing in GoDaddy server and you are using Session variables in the routing pages you should add Session module (manually)

<httpModules>
<add name=”Session” type=”System.Web.SessionState.SessionStateModule”/>
<add name=”UrlRoutingModule” type=”System.Web.Routing.UrlRoutingModule,System.Web.Routing,Version=3.5.0.0,Culture=neutral,PublicKeyToken=31BF3856AD364E35″ />
</httpModules>

<system.webServer>
<modules>
<remove name=”Session” />
<add name=”Session” type=”System.Web.SessionState.SessionStateModule”/>
<remove name=”UrlRoutingModule” />
<add name=”UrlRoutingModule” type=”System.Web.Routing.UrlRoutingModule,System.Web.Routing,Version=3.5.0.0,Culture=neutral,PublicKeyToken=31BF3856AD364E35″ />
</modules>
<handlers>
<add name=”UrlRoutingHandler” preCondition=”integratedMode” verb=”*” path=”UrlRouting.axd” type=”System.Web.HttpForbiddenHandler, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a” />
</handlers>
</system.webServer>

Note : Always use ResolveUrl  for images OR css file or links to get the virtual path of the folder from the web site root  in the routing pages.
for ex :  [ ResolveUrl (“~/images/logo.jpg”) ]

You can download the entire article from here

or copy paste this url  http://www.4shared.com/file/230713773/954be86b/UrlRouting.html  in to your browser.

Hope this help and If you have any comments, please feel free to write your feedback.

Thanks
Deepu

<system.webServer>
<modules>
<remove name=”Session” />
<add name=”Session” type=”System.Web.SessionState.SessionStateModule”/>
<remove name=”UrlRoutingModule” />
<add name=”UrlRoutingModule” type=”System.Web.Routing.UrlRoutingModule,System.Web.Routing,Version=3.5.0.0,Culture=neutral,PublicKeyToken=31BF3856AD364E35″ />
</modules>
<handlers>
<add name=”UrlRoutingHandler” preCondition=”integratedMode” verb=”*” path=”UrlRouting.axd” type=”System.Web.HttpForbiddenHandler, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a” />
</handlers>
</system.webServer>
Advertisements

24 thoughts on “Url Routing in Asp.Net Web Forms

  1. Hey…I have GoDaddy shared hosting. I was having problems so I called them and they are telling me that the System.Web.Routing namespace is not available with a shared hosting plan and any dll that needs to be registered with IIS is not allowed. What kind of hsoting plan do you have with GoDaddy?

  2. i edited the web.config file like you said but it didn’t work for me…
    i get internal 500 error if i try to go the routed urls…
    how do i select integrated mode pipe line by the way?

  3. This is the only complete article I’ve seen, that shows you how to retrieve the parameters; in asp.net 3.5 all the other articles I looked at kept showing me solutions for asp.net 4. Thanks a mill, great job!

  4. thanks,this is what i’m looking for..
    but,i’ve got one problem. i run it through visual studio,it works. but when i publish it and install on IIS6 (local), it didn’t work, i’ve got “the page cannot be found” error message. what should i do?
    i’m sorry for my bad english,, 🙂

  5. Great write up!
    Worked for me first go ’round =)

    Instead of doing a member list page, I simply wanted to try and create a default route for my Default.aspx page and it worked.

    Is there a way to remove the ability to directly map to the folder structure? For instance, I’ve now made it so that myWebsite.com/Home is the virtual route to myWebsite.com/Default.aspx but that direct folder route still also works. Can I make it so /Home redirects to my Default.aspx page but going to Default.aspx directly results in a 404-error or something?

    1. Yest it is possible, adding one more route like below..

      routes.Add(“Home”, new Route
      (
      “Home/”,
      new MemberRouteHandler(“~/default.aspx”)
      ));

      Hope this helps
      Thanks
      Deepu

  6. Hi Deepu,

    I tried above code it won’t work for me.

    routes.Add(“Home”, new Route
    (
    “Home/”,
    new MemberRouteHandler(“~/Default.aspx”)
    ));

    Please reply ASAP.

    AJAY

  7. Nice one but i am facing some prb like that if i add multiple router method and i access this page using response.redirect then same page are redirect on same parameter condition’s .
    can i add router name in response.redirect method or some other, i am using asp.net 3.5.
    please help me.

  8. Hi,

    I was reading your article and I would like to appreciate you for making it very simple and understandable. This article gives me a basic idea of URL Routing in ASP.Net 3.5(IIS7) and it helped me a lot. Thanks for sharing with us. Check out this link too its also having nice post with wonderful explanation on URL Routing in ASP.Net 3.5(IIS7), for more details check this….

    http://mindstick.com/Articles/9992a0bc-90f5-4f04-823a-31f901b61643/?URL%20Routing%20in%20ASP.Net%203.5%28IIS7%29

    Thank you very much!

  9. Hi There, I hosted my asp.net 4.0 web site on GoDaddy and facing issues like 404 page not found.
    When I am entering url manually, that is full URL (not friednly url), site is working but when trying to access as per route table not working.

    I tried solution mentioned by
    http://www.thejackol.com/2011/03/24/url-routing-problem-with-asp-net-4-on-godaddy-iis-7/
    but it didn’t worked

    I noticed you have sent web.config to many. Can you share the same with me also>

    Regards
    Varun

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s