Click here to Skip to main content
Click here to Skip to main content

URL rewriting using ASP.NET routing

By , 7 Jul 2009
 

Introduction

Sometimes we need to have search engine friendly URLs for our application. In ASP.NET (before ASP.NET MVC/3.5 SP1), we had to use some third party tools like URL rewriter, which work fine but require wild card mapping in IIS and have issues with IIS7.

ASP.NET MVC has introduced the System.Web.Routing assembly for rewriting URLs; now, it is included in ASP.NET 3.5 SP1. Using the routing assembly, you can have search engine friendly URLs like http://mysite.com/add_new_user.

Now we can use the System.Web.Routing assembly in our ASP.NET website to create such URLs. (Please see the download file from above.)

Using the code

You can find the complete source code from the download provided above (url_routing.zip). Unzip the file and open using Visual Studio 2008 (open the website wizard), and you will need to browse to the folder "url_rout" (that should contain the web.config file).

First of all, you have to add a reference to System.Web.Routing in your application, or you can add the following line in the web.config (under the assemblies section). You must have ASP.NET 3.5 SP1 installed.

<add assembly="System.Web.Routing, Version=3.5.0.0, 
     Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

Now, we need to create different routes in global.asax. In the first route "Add_New_User", we don't have any parameters; but in the second route "User/{name}", we have a parameter called name.

void Application_Start(object sender, EventArgs e) 
{
    // Code that runs on application startup
    RegisterRoutes();
}
private static void RegisterRoutes()
{
    System.Web.Routing.RouteTable.Routes.Add(
           "Add_New_User", 
           new System.Web.Routing.Route("Add_New_User",
               new RouteHandler("~/RegisterUser.aspx")));
    
    System.Web.Routing.RouteTable.Routes.Add(
           "user", 
           new System.Web.Routing.Route("User/{name}",
               new UserRouteHandler("~/DisplayUser.aspx")));
}

UserRouteHandler and RouteHandler are classes that implement IRouteHandler, as shown below:

public class UserRouteHandler : IRouteHandler
{
    public UserRouteHandler(string virtualPath)
    {
        _virtualPath = virtualPath;
    }

    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        var display = BuildManager.CreateInstanceFromVirtualPath(
                      _virtualPath, typeof(Page)) as IUserDisplay;
        display.UniqueName = 
          requestContext.RouteData.Values["name"] as string;
        return display;
    }

     string _virtualPath;
}

You will notice that IUserDisplay is an interface which implements IHttpHandler:

public interface IUserDisplay : IHttpHandler
{
    string UniqueName { get; set; }
}

IUserDisplay has to be implemented by the page to be rendered (DisplayUser.aspx, in this case) as shown below, so that the unique identifier (UniqueName, in the case) or parameter will be found in the page, which can be used to show the appropriate data (like the query string).

public partial class DisplayUser : Page, IUserDisplay
{
    public string UniqueName { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (UniqueName != null && !UniqueName.Equals(""))
        {
        //do some coding
    }
    }
}

Points of interest

I have found that all samples and tutorials on this topic are for either ASP.NET MVC applications or web projects, and nothing if I want to create a normal ASP.NET website (however, there are not much differences between them). Here are some useful links for routing:

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

bajpai.anurag
Software Developer (Senior) Neev Information Technologies Pvt Ltd
India India
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralProblem With UrlRotingmemberShrivastva18 Feb '11 - 2:21 
Hi friend,
In the demo all is working fine but,displaying resorce not find renaming the folder with "." [example '/www.url_rout']
 

 
Server Error in Server Error in '/www.url_rout' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
 
Requested URL: /www.url_rout/Add_New_User
 
Version Information: Microsoft .NET Framework Version:2.0.50727.4927; ASP.NET Version:2.0.50727.4927 Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
 
Requested URL: /www.url_rout/Add_New_User
 
Version Information: Microsoft .NET Framework Version:2.0.50727.4927; ASP.NET Version:2.0.50727.4927
 

D'Oh! | :doh:
QuestionIIS settings for URLREWRITINGmemberneil@euclid3 Nov '10 - 1:49 
hi
thanks for the wonderfull code
 
but i'm finding it difficult to implement it
when i realease my code and create the virtual directory the first page i'm able to access but then when i click on a link to some other page it shows 404 page not found.
I think there are some settings to be done for the same
coz the site works perfectly fine in Visual studio
 
Please help me out its urgent
AnswerRe: IIS settings for URLREWRITINGmemberneil@euclid9 Nov '10 - 1:22 
all Done
need to do mappings in the configurations section of the IIS
Wild card mappping to be precise
thanks and regards
Nilesh patel
QuestionProblem with master page and user controlmemberjinal.mehta31 May '10 - 20:32 
Hello sir,
 

i have master page and user control in my page so whenever my page is load then user control and master page is load so many times.. please give me a solution for same.
AnswerRe: Problem with master page and user controlmemberbajpai.anurag1 Jun '10 - 4:24 
Are you using url rewriting or this is a general issue ?
If you are using url re-writing then may be you have defined interfaces incorrectly.
Anurag Bajpai

QuestionHow to combine UrlRoutingModule with AjaxControlToolkitmemberusuphan14 Dec '09 - 5:23 
If I try to combine UrlRoutingModule with AjaxControlToolkit,I get error ASP.NET Ajax client-side framework failed to load.
GeneralBest article on ASP.NET Routingmembernomi198427 Oct '09 - 3:13 
Just to say many thanks for sharing your knowledge. I've been looking for routing toturial for some time but most of the articles are overally complicated but not yours. Got to be the best toturial on this topic. Well done. Thumbs Up | :thumbsup:
GeneralA big ThanksmemberBjorn van der Neut21 Aug '09 - 10:40 
This was just what i was looking for!
 
Great stuf and I am allready building it into my site http://www.thevictory.nl/tafeltennis/
 
Thanks again!
Bjorn
QuestionInterestingmemberstixoffire8 Jul '09 - 5:17 
While I have not tried the code yet I have some questions.
 
Postbacks - does this handle them correctly ?
 
Virtual Mapping (you are using Global asax -
 
What if I wish to have virtual urls depending on the category link clicked. In other words the mapping is dynamic.
AnswerRe: Interestingmemberrippo13 Jul '09 - 21:07 
Ditto on the questions, I would love to know about dynamic mapping via an external link or database entries.
 
Rippo

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 7 Jul 2009
Article Copyright 2009 by bajpai.anurag
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid