Subscribe to RSS Feed

C#, ASP.NET, and Your Mom

How To: Use URL Rewriting in ASP.NET

URL rewriting is the practice publishing a cleaner URL for your ASP.NET web application. There are many reasons you might want to do this, chief amongst them being search engine optimization and human readability. This article will show you how to use URL rewriting to hide your ugly URL while retaining the power and structure of your existing ASP.NET application.

What is URL rewriting and why should I care?

As I said before, URL rewriting is a practice that lets you publish a cleaner URL to the world, but that may not be clear. In other words, you can "point" or redirect any URL a user accesses to an existing ASP.NET page in your application. Take a look at this URL:

http://www.joshjordan.com/index.php?i=321

That is my standard, ugly URL. Now look at this one, which is the result of URL rewriting:

http://www.joshjordan.com/google-chrome-beta-20-released-321

Which one looks better to your eye? Probably the second one. It gives the user some important information about what might be on that page. Which one looks better to a search engine? Definitely the second one. Search engines actively try to ascertain information about the contents of a page based on many criteria, and the URL is no exception. Google, Yahoo, and Live Search all pull common keywords out of the URL, and if you want traffic on your site (and lets face it, who doesn't?), you want to have a good page ranking with these search engines. Search engine optimization is a rapidly changing field, but providing search engine-friendly URLs is a practice that is going to consistently drive traffic to your site by making your page's search relevancy higher.

One worry that you may have is that we are only redirecting the user to a new page with URL rewriting. This would result in a few problems. Firstly, the URL shown in the user's browser would change to the ugly URL as soon as the access the page, and thus, our highly-guarded secret is exposed. Worse, they might link that URL to another person, which means they are giving out the ugly URL, and our effort would've been wasted. Finally, a search engine would see both the clean URL and the ugly URL, which could result in splitting your page ranking between the two of them. Don't worry, your ugly URL will not be exposed. URL rewriting in ASP.NET (at least the way I'll show you) does not redirect the HTTP request to another page, it actually answers the request at the clean URL with one from whatever page you'd like, all without any knowledge of the rewriting on the user's side.

Okay, URL rewriting is a good idea. How do I do it?

Well, that's simple. Just call the HttpContext.RewritePath() method from the Application_BeginRequest() event handler in your Global.asax file.  What is that you say? You don't have a Global.asax file? Okay, I'll walk you through an example.

I am currently working on a project where my site has a county-based taxonomy. That is, the main page for a county is the primary unit of organization. Thus, I want to provide a provide a URL that includes the name of the county. Unfortunately, my otherwise well-designed data driven application will only provide me with something like this by default:

http://www.myproject.com/County.aspx?ID=5

However, I'd like it to look something more like this (for my home county of Rensselaer):

http://www.myproject.com/Rensselaer

I could, of course, just make a directory or Aspx page for Rensselaer, but I already have my application working so nice and cleanly! I don't want to create more pages that I have to maintain. So, I choose to use URL rewriting to handle this situation.

To get started with URL rewriting, create a Global.asax file. A Global.asax file is a set of event handlers for application-level events, such as client sessions beginning, client sessions ending, and (ah-ha!) URL requests beginning. To create this file, add a new file to your project and select Global Application Class. Leave the filename to its default.

Adding a Global.asax file

Note that you will be unable to select Global Application Class if a Global.asax file already exists in your project. Now that we have this file, we want to add code to the Application_BeginRequest() event handler that handles our URL rewriting. In this example, I will simply route based on the contents of the incoming URL. If the URL contains one of my keywords, I will route it appropriately. If not, I will do nothing and the request will be processed normally (either landing on some existing page, or producing a 404 error).

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            //Friendly URL keywords
            string[] counties = { "Albany", "Rensselaer", "Montgomery" };

            //Loop through keywords
            for(int i=0; i<counties .Length; i++)
            {
                //Check to see if the URL contains this keyword
                //Remember to use case-insensitive logic!
                if (Request.Url.ToString().ToLower().Contains(counties[i]))
                {
                    //If a keyword was found, rewrite and break out
                    Context.RewritePath("~/County.aspx?CountyID=" + i);
                    return;
                }
            }
        }

I use the string.Contains() method and a string array in this simple example. I route to the indices of the string in the array. Note that the incoming URL could have a mix of capital and lowercase letters, so you should always use string.ToLower() when performing comparisons in this case. In a more realistic example, a Dictionary of strings and integer ID's may be necessary, or even a connection to a database to retrieve keywords. Some useful objects you should play with to extract data from the incoming request:

  • Request.URL: The entire incoming URL, used above.
  • Request.QueryString: The parameters, provided as key-value pairs, beyond the "?" in the URL. Note that this object has string and int-based indexers.
  • Request.URL.ToString().Split('/'): A string array split into tokens based on forward slashes. This is useful because it allows you to look at the individual directories and files requested beyond the domain.
  • Advanced Routing

    Since you can write any code you like in the Application_BeginRequest() method, there is a lot you can do here. As I mentioned, you could use values from a database, or parse the URL into multiple different pieces to control your routing. If there is sufficient demand, I will write another few articles that talk about advanced topics in URL rewriting, touching up on those topics as well as setting up virtual directories, preserving the query string, handling image requests by wrapping them with HTML, efficiency in URL rewriting, etc. Please give me some feedback if you want more!

    Other URL rewriting methods for ASP.NET

    Other methods exist for URL rewriting, but I didn't mention them here both because I haven't tried them and because they seem much less ideal than the solution I gave above. If you are looking for other ways to do this, be on the look out for rewriting using the Request.PathInfo object, which uses a URL that looks something like this (which is still ugly to me):

    http://www.myproject.com/county.aspx/Rensselaer

    There are Web.config approaches, but they are less programmatic and do not give you dynamic control over your routing. I want to write code to do this! If I was doing it statically, I might as well just use new Aspx pages. Finally, you can use ISAPIRewrite to have your IIS server do the routing for you. Again, this is too static for me. For more information on these approaches, check out this amazing post on Scott Guthrie's blog.

    Notes

    I just wanted to point out what a big deal URL rewriting is becoming these days by pointing out that it is one of the main concepts behind the ASP.NET MVC framework approach. Every ASP.NET MVC tutorial I've seen has started with the routing module, which provides a facility for automatically tokenizing the URL into separate pieces to decide how to route the request to the View, including default values for each piece. Can you tell I'm excited about ASP.NET MVC?

    • Share/Save/Bookmark

Comments

  • Chris said:

    "Which one looks better to your eye? Probably the second one. It gives the user some important information about what might be on that page. Which one looks better to a search engine? Definitely the second one."

    Then why should you even bother with URL rewriting if both concerned parties prefer the second choice?

  • Josh Jordan (Author) said:

    Well, there are many more parties concerned with your application than just the user and a search engine. The developer and the developer's organization are also major players. Plain and simple, it is generally much easier (read: faster, more robust, and less error-prone) to structure your application in such a way that it revolves around receiving numeric IDs in the querystring rather than "prettified" URLs. As mentioned in the article, URL rewriting prevents you from having to create a separate Aspx page for each friendly URL that you want to accept.

    Perhaps I misunderstood the question. If the second choice you are referring to is the result of URL rewriting, why not bother with URL rewriting?

  • James Craig said:

    I just wanted to point out that there is no difference to doing what you propose above with an HttpModule and your Global.asax code. With the HttpModule approach, you'd simply tie into the Application.BeginRequest event and go from there. Either way the code is firing during the same event...

  • Josh Jordan (Author) said:

    James,

    You're absolutely right. What I meant to say was that there are HttpModule approaches that can be linked up through the Web.config file that are less dynamic. Indeed, the Global.asax approach really is an HttpModule approach. Thanks for the clarification.

Trackbacks



Recent Archives
1 24 vintage marx slot crystorama royal flush mount 100 hand video poker download free bonus keno thepokerguide games eva vig contract type per line item free bonus mulit payline slots shotgun straight up awp drug pricing bacardi baccarat decanter millennium rum 100 islands poker run seebeforeyoudie.net 1790 s food crap strayer.info buy video poker games sctravel.net batman dark knight wallpaper joker oscn.org 1985 vw joker pirate treasure jewels rob thomas street corner symphony plantcultures.org 1-1 2 wr galvanized roof deck nominal amp per line formula casino on line with bonus slots card credit high people risk bangmyindianwife.com blue sky blue sport fruit punch blue dot jackpot winner ann kennedy full house resort royal flush industries inc 2 deck blackjack in aruba 72-ton the joker 100 plastic poker cards south africa back masage leads to hand job 10 dollar deposit minimum online casinos bulldog bucks card midland high school computer game poker share video ware idol contestant sings paula straight up alien gaming machines bmc remedy wild card 1 gallon flush toilet queen jewels sweden aaaokwebmember.com century twenty one seymour in braless pokies 2007 jelsoft enterprises ltd let it ride bachman overdrive clifford the big red dog game aristocrat 50 lions pokies game download ameristar casinos omaha ne 12 tube poker chip tray aztec gaming machine 1 club casino nd bonus coupon 5 cent roulette high or low impedance back in gods hand three kinds of fuels erection straight up gastonia century twenty one aces and jokers houses for sale century twenty one crusty demons the hard way let it ride bto champagne and sherbert fruit punch recipe burns supper croupier queens jewels game brochure five first saturdays devotion free full house md episodes wild deuces acompa antes san gil blguitar.com royal flush band backgammon big six learning free bonus feature slots only chocolate red pussy dogs free wild card keno download full tilt poker bonus code 1 2 inch foam dice baccarat candle fighting squadron one twenty four moonlighters gocabins.com different ways to build a house first five books of hebrew bible 2006 victory jackpot casino bonus poker games 3 line video poker 50 play video poker strtegy card credit high processor risk princetonnationalsurveys.net 52 cards plus joker 1 43 scale slot cars forever twenty one atlanta nexi.com baccarat back-gammon-online three kinds of symmetry alex kingston croupier nude effinghamcounty.org clifferd the big red dog balsamic vig nola is acid ph high or low deuces wild video poker payout in4mador.com handheld bonus poker game boston red dogs candid teen bikini pokies all that crap at school 3pt root rake chet baker the hard way album 1995 waverunner 1100 flush kit gate way profile 3 hard drive circus by the sea my way frank sinatra hard cover redlightemail.com alian ante farn fast way to lose weight successfully back of your hand guitar tab mineweb.co.za giada de laurentiss pokies first five huracanes in 2004 let it ride strategy adsneeze.com big six naacp air anime christian crap spellspot.com alabama high school report cards free vig tits 777 online gambling 1924 studebaker big six duplex phaeton 1 1 2 inch flush pull .8 gallon flush toilet vast aire deuces wild ron vig cytonox triple berry fruit punch best way to clean a house all casinos in florida black jack video poker gambling 3 the hard way jim brown worden.com 1 1 2 galvanized metal deck three kinds of plate boundaries audio clips of the joker $1.00 minimum deposits online casinos pot of gold gaming machines georgia baccarat acessories three kinds of spyware all the crap i do mp3 betting line per nfl fruit punch for a party best way to claim lotto jackpots arnold snyders blackjack half way house decatur al full episodes of house online official western big six conference statistics reformat address list one per line absolute poker reload bonus codes best way to air a house credithelpexpert.com big six accounting firm jokes 1 red dice bcfls.org against backgammon computer play poker onlinefreerolls bonus gamingonlinewin party poker bonus code no deposit 2007 victory vegas jackpot jackseattle.com batman beyond the joker acompa antes merida mexico card high counting blackjack ante bellum etymology acompa antes independientes en bogota pcl.com croupier job croupier uddannelse jackson five first album awp inflation by astra zeneca aw crap pictures 1970 sylvan pontoon auto money download free back hand spring on the beam all that david copperfield kindof crap adam faith and the roulettes acompa antes guadalajara mexico a picture of joker form batman charlotte video poker adult sex roulette age for gambling stockholmwisconsin.com harley deuces wild license plate bette midler jackpot dvd too high or too low tsh croupiers casino lac leamy 2 gb high speed sd card 007 casino royale quotes australian actor played joker bellevue iowa pirate treasure storey 10 blank decks skateboard decks club twenty one realty astuce roulette baby books first five years 10 person folding poker table backgammon bear off rules 1 24 scale slot cars bodies beat casino in online roulette scam equinoxfitness.com 2010 bingo sites nickelback song learn the hard way best ways to burn fat fast usb video cards cause slow down peeingclips.net bring it on keno apps for blackjack corner of a street queens jewels pearl clasp 1 32nd scale slot cars big six and super three 1985 vw westfalia joker southeastern lefthand corner of main street full columbia house movie list affiliate best gambling 4 x 4 bingo grid clifford the big red dog activities about internet gambling cheapest way to heat a house tennesseetrustee.com adjustable lawn rakes louisville slugger hands back advanced craps yourmilfporn.com ben vig ballarat pokies how to make caribbean fruit punch ameristar casinos kansas city inforadionet.com fruit machines free online all jackpot casino promotion code deuces poker strategy video wild xpressnet.com three kinds of love movie quote 110 tricks svengali deck carthage central high school report card antique 3-in-1 roulette acura 3.2 engine is crap 17th european backgammon championships gay pick up straight guy awp governance arrangements uk jane krakowski pokies bonuscode onlinetournament keno blackjack abbotsford bingo hall in canada 16mm razor edge white dice american idol wild card winners a blackjack 1978 ford f350 stake rake queen art jewels backgammon board game rule 2006 victory cory ness jackpot bar le full house magog rallyformusic.com 14g real clay poker chips 1100stx flush directions cooling system boston red sox dog jackets owasso.com cole bothers circus of the stars jessica-alba-naked.com fast way to lose fat backgammon agourahills can dogs see red acompa antes colombia fast way to burn calories ancient pirate treasure authorized vgt gaming machine servicers free bonus round slots card diet high low protein baccarat 250d 250a 1 32nd scale slot cars cold case files bonus game backgammon acey ducey rob thomas street corner syphony haiku number of syllables per line biblefacts.org roman vig amusements fruit machines 21 dice game rules back hand job armenia backgammon backgammon basics 1 24 slot car speed tricks rita vig ace point backgammon budget free claims money state fox house full episode age requirment for michigan casinos bonus code poker stars veryfunnycartoons.com 1 32 artin slot car all california casinos rob thomas street corner symphony first five presidents test 100 hand poker cliferd big red dog apple casinos facorelogic.com ama big six racing cinoche.com 4,5,6 dice game downloads free poker strip video addtron awp 100 driver good vig best celebrity nipples or pokies photos ante a libro firenze cheap ways to build a house 10 x 10 deck kit yapclub.com free slots bonus game per 6 cell line 115 poker chips jediknight.net formula twenty one duderanch.org its hard to find a way deuces wild basic strategy 1957 ferrari testerosa pontoon fender corner street plymouth ma no deposit bonuses slots bankruptcy free money creative ways to swap houses six pack and big white cock ad ante deluvian nd bonus slots wholovesmoney.com always win at roulette ice t straight up free bonus slot games pirate treasure activities for kids freefarmsex.net fast way to kill lawn donnaskorner.com batman and jokers relashionship 3rd war keno valentino croupier terms drop per foot sewer lines 40 the hard way dvd batman beyond return of the joker alicia rhodes seven the hard way age gambling aruba 6d dice download free game poker video baccarat bird ass striping games without blackjack alabama awp settlement dangerous ways to lose weight fast cherrymaster fruit machine hacking can dogs eat red licorice glaciermt.com 2007 blackjack ford mustang are stock markets costly casinos pirate treasure activities for kids century twenty one new jersey 1994 185 lowe pontoon ernrcr3.com