URL Routing with reverse rewriting with Framework 3.5 sp1

AID: 2365
  • Status: Published

10100 points

  • Byzadeveloper
  • TypeTutorial
  • Posted on2010-01-30 at 13:26:26
Awards
  • Community Pick
  • Experts Exchange Approved


Introduction

This article will explain how to use URL Routing dot Net Framework 3.5 sp1 (and I guessing eventually framework 4) and C# ASP .NET. URL Routing is the ability to format your url strings into friendly names and using the data passed in as if they were parameters passed to your page.

URL Routing is Microsoft’s answer for URL rewriting, and speaking from some sort of experience it is a lot easier and a lot less code than URL rewriting as well.

Why? You might ask... Simple reason – Search Engines rates your site higher than sites which still use query strings.

Starting out

A few things you need to do in order to use URL Routing (in VS 2008 sp1) :

1.    You need to make reference to “System.Web.Routing” (this came with Framework3.5 sp1)
2.    You need to have a web.config file (should be there by default unless you have nuked it)
3.    You need a Global.asax file
4.    You need the 2 Helper classes that I have written to ensure that the app works. The are very simple files and you can create your own or mod the simple ones I have created.

        a.    IRoutablePage.cs
        b.    RoutingHandler.cs
5.    In the web.config file add the following line to <httpModules> in <system.web>

<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
                                    
1:

Select allOpen in new window



 Note:  this will eventually need to be modified to run with framework 4.0, 4.5, 4.6, 4.7 etc... J
6.    Then change  the following in the <system.webServer> section of the config file.

<modules runAllManagedModulesForAllRequests="true">
                                    
1:

Select allOpen in new window



7.    You need to add the following in the <system.webServer> section of the config file in order for IIS7 to understand the hosting options.

<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
                                    
1:

Select allOpen in new window




Getting into it

Now that your setup is semi-complete we can get onto the good stuff.
Go into your global.asax file and add the following:

public static void RegisterRoutes(RouteCollection routes)
        {
            // StopRoutingHandler for .axd and .asmx requests
            routes.Add( new Route( "{resource}.axd/{*pathInfo}", new StopRoutingHandler() ) );
            routes.Add( new Route( "{service}.asmx/{*pathInfo}", new StopRoutingHandler() ) );
 
            // Add some named handlers
            routes.Add("Blog", new Route("Blog/{entrydate}", new RoutingHandler("~/Blogs/ViewBlog.aspx")));
        }
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:

Select allOpen in new window



RegisterRoutes is going to be the default Microsoft function name and signature in the future releases. The first 2 lines of code there are saying that we want to add to our route table (by the way – this is how routes are managed using URL Routing) routes for all files that end with .axd and asmx. Then we are saying (with: StopRoutingHandler) that our URL Routing should ignore these types of files.

In the last line of code we add a route called “Blog” and we want all urls that look like “Blog/xxxxxx” to map to the Page Path ~/Blogs/ViewBlog.aspx. We are also declaring a variable called entrydate. We could of added more by doing something like this: "Blog/{entrydate}/{username}/{second}".

RoutingHandler is my custom implementation of IRouteHandler which is the 2nd paramater required to create a Route object.

Finally to start this whole thing off we need to call

RegisterRoutes(RouteTable.Routes);
                                    
1:

Select allOpen in new window



From our application_start function.

The only thing left to do is ensure that Blogs/ViewBlog.aspx  implements IRoutablePage in the following way:

public partial class ViewBlog : Page, IRoutablePage
    {                   
        /// <summary>
        /// Implementation of IRoutablePage
        /// </summary>

        public RouteValueDictionary RouteData { get; set; }
                                    
1:
2:
3:
4:
5:
6:
7:

Select allOpen in new window


Using the Variables from c# code

Then using the variables from the page is also very simple. If the url was http://blablabla.com/Blog/24 the value of RouteData["entrydate"] would be 24.

protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write("Wassup " + RouteData["entrydate"]);
        }
                                    
1:
2:
3:
4:

Select allOpen in new window


 

I have uploaded a very simple and small project for demonstration.

Reverse writing the URL


A function called ReverseWriteUrl has been added to the global.asax file. What this does is reverse writes the URL for you. So if someone types into the address bar http://.../Blogs/ViewBlog.aspx?entrydate=20090801&UserName=Jarrod this will be rewritten as /Blog/20090801/Jarrod etc...

All you need to do is call the function as follows:

protected void Application_BeginRequest(object sender, EventArgs e)
        {
            ReversewriteUrl (HttpContext.Current);
        }
                                    
1:
2:
3:
4:

Select allOpen in new window


 
This will then check your routing table and reverse write all direct page calls to the virtual directory.

Originally posted @ http://www.zadeveloper.com/Articles/31
Asked On
2010-01-30 at 13:26:26ID2365
Tags

ASP C# URL Rewriting URL routing

Topic

Programming for ASP.NET

Views
5147

Comments

Add your Comment

Please Sign up or Log in to comment on this article.

Join Experts Exchange Today

Gain Access to all our Tech Resources

Get personalized answers

Ask unlimited questions

Access Proven Solutions

Search 3.2 million solutions

Read In-Depth How-To Guides

1000+ articles, demos, & tips

Watch Step by Step Tutorials

Learn direct from top tech pros

And Much More!

Your complete tech resource

See Plans and Pricing

30-day free trial. Register in 60 seconds.

Loading Advertisement...

Top ASP.NET Experts

  1. CodeCruiser

    420,756

    Wizard

    2,010 points yesterday

    Profile
    Rank: Genius
  2. kaufmed

    283,163

    Guru

    500 points yesterday

    Profile
    Rank: Genius
  3. BuggyCoder

    269,283

    Guru

    3,600 points yesterday

    Profile
    Rank: Sage
  4. tommyBoy

    171,028

    Guru

    0 points yesterday

    Profile
    Rank: Genius
  5. TheLearnedOne

    165,990

    Guru

    0 points yesterday

    Profile
    Rank: Savant
  6. ddayx10

    139,847

    Master

    0 points yesterday

    Profile
    Rank: Sage
  7. MlandaT

    122,463

    Master

    0 points yesterday

    Profile
    Rank: Genius
  8. techChallenger1

    107,384

    Master

    0 points yesterday

    Profile
    Rank: Guru
  9. navneethegde

    90,197

    Master

    0 points yesterday

    Profile
    Rank: Wizard
  10. Masteraco

    82,909

    Master

    0 points yesterday

    Profile
    Rank: Wizard
  11. Dhaest

    80,693

    Master

    2,000 points yesterday

    Profile
    Rank: Genius
  12. vs00saini

    76,565

    Master

    0 points yesterday

    Profile
    Rank: Wizard
  13. Chinmay_Patel

    73,407

    Master

    0 points yesterday

    Profile
    Rank: Genius
  14. stephanonline

    69,461

    Master

    0 points yesterday

    Profile
    Rank: Wizard
  15. nishantcomp2512

    68,521

    Master

    0 points yesterday

    Profile
    Rank: Wizard
  16. srosebabu

    67,676

    Master

    0 points yesterday

    Profile
    Rank: Guru
  17. markmiddlemist

    65,828

    Master

    0 points yesterday

    Profile
    Rank: Master
  18. jacko72

    65,660

    Master

    0 points yesterday

    Profile
    Rank: Genius
  19. sammySeltzer

    64,318

    Master

    0 points yesterday

    Profile
    Rank: Genius
  20. wdosanjos

    59,639

    Master

    0 points yesterday

    Profile
    Rank: Genius
  21. mroonal

    58,080

    Master

    0 points yesterday

    Profile
    Rank: Sage
  22. mas_oz2003

    56,140

    Master

    0 points yesterday

    Profile
    Rank: Genius
  23. Rouchie

    55,801

    Master

    0 points yesterday

    Profile
    Rank: Genius
  24. Lalit-Chandra

    54,514

    Master

    0 points yesterday

    Profile
    Rank: Master
  25. EaswaranP

    54,203

    Master

    0 points yesterday

    Profile
    Rank: Guru

Hall Of Fame