URL Rewriting and Routing in ASP.NET 4

by Dmitry Kirsanov 9. December 2011 21:37

How to make the URL of your page look more user-friendly or just make it self-explanatory? And anyway – look different from what it really is? In ASP.NET version 4 it’s easier than ever.

Why would we need that feature anyway?

It’s been quite popular trend in web development since the very beginning of dynamic Web – first, we didn’t want anyone to see the extension of our files, as this posed a security risk. Anyone, who could see that our page is actually an ASP page, would understand that you have Internet Information Server, which was considered “dangerous” at that time – not even because it was too bad, but because Windows NT 4 Server was user-friendly enough so people wouldn’t need to be MCSE in order to install and run web server. It wasn’t hard for Linux either, but Apache didn’t offer any dynamic contents out of the box.

So, the first reason was to disguise the fact we are running Windows. Now, in year 2011 this sounds crazy, but back then, in the end of 90s, it was our reality. We didn’t want any attention to the technology we were using.

But at the same time, the same trend was developing also among the PHP programmers, who didn’t want people to remember the extension, and overall tried to make URLs look more “user friendly”, as people were much less computer-literate 12 years ago.

Eventually, first URL rewriters appeared – either as CGI or ISAPI extensions, they offered basic dictionary to hide existing pages behind keywords, so you could type http://example.com/about and this would display the about.asp page instead, without users being aware of it. Some JavaScript solutions existed as well, but they became unusable after browser makers switched that possibility off, because it was widely exploited by scammers.

It was easier to print on documents and spell by phone, but people also started to look at the URL portion of the search engine result (at that time it was either AltaVista or Yahoo) – and they would rather click on URL they could read. That’s when Search Engine Optimization, or SEO, started to add reason to transform URLs into something more descriptive than server-side script file name.

Website owners, especially those who are managing web developers and paying their salary, wouldn’t easily accept the idea of wasting a few days of work (read: money) and decrease the web server performance in order to make links to their pages more “clean” or “memorable”, or, say, easy to copy and paste on forums and tweets. Oh, wait, we didn’t have tweets and blogs at that time. So as you can see, the sense behind the feature was accumulating gradually and therefore didn’t become a part of the platform… Until now.

It’s now, in 2011, when search engines will position your page higher if there is a keyword in the URL, not only in the title, and people are almost always looking into the actual address, because they are afraid of link redirectors – at least those of them which hide the target URL (that’s, actually, almost all of them). So rewriting the URL or having multiple dynamic URLs for a single page or even having dynamic page with dynamic URL is a huge advantage these days.

So how we gonna do that?

Until the ASP.NET version 4, the only way you could do that is by installing a 3rd party add-on, like UrlRewriter.Net.  It wasn’t as simple to implement as most other functions of .NET, so not everyone used it at all, not mentioning “used effectively”.

In ASP.NET version 4, released in April of 2010, a new feature was implemented, named ASP.NET URL Routing. It brings all the advantages or URL rewriting and adds more, making it a more unique routing instead. There is no direct mapping between the URL and the file anymore, as you can generate the output dynamically based on the URL provided. So, for example, instead of this:

http://example.com/store/view_item.aspx?itemid=13705

You could write something like that:

http://example.com/notebooks/asus/eeePC/1205P

Which one of them would get more clicks, do you think? And in the example above, we don’t even have the notebooks folder in our server.

How it works

In ASP.NET 4, it is done via the RouteTable collection.  You have to initialize it when your ASP.NET application starts, by modifying the global.asax.cs (in case you’re working with C#) file of your ASP.NET website.

image

It will look like this. As you can see, we’re initializing the collection of routes when the application starts, and during that initialization, we add 3 rules.

The basic rule, number 2, is routing all requests for “/home” to “home.aspx”. But the visitor will only see the “http://example.com/home” as the page URL and won’t know the name of the exact page which prepared the output for him.

The last rule allows us to type “default.aspx” which in fact will be managed by “home.aspx” page.

And the first rule is the most complicated one – it allows us to type anything (like “http://example.com/ABCDEF”) and as the result of that, “product.aspx” will display the information about the product ABCDEF. Interesting in this rule is that we’re using the regular expression to identify the string. That way we can create a rule, which will only be triggered if the page name is an e-mail address or any other structured information.

However, in the  example above we are using virtual folders, like “notebooks” and “asus”. It could be done by fourth rule, stating something like that:

image

The routing engine will split the URL into parameters and you will be able to consume them in your page. No additional code, like low level HttpHandler object, is required.

That’s how we  set up the rules. But how to consume that data? First thing that comes to mind – perhaps they are given to the processing page as HTTP parameters, like POST or GET ones? No. There is another way to get these parameters, and this is how we do it:

image

Simple, isn’t it? But what if you don’t know how many segments you’ll have in your URL? Like instead of “/notebooks/asus/eeePC” you could have also “/notebooks/asus/12inch/eeePC” ? As always, just another rule, and this time it would look like:

image

In this case, anything that’s after “tags/” will be considered as collection of parameters and will be returned as slash-delimited list named “tagnames”. So you will only have to retrieve that one parameter as shown above and then split it by “/” character.

That’s almost it. There are more advanced features in URL routing and you can see them all in MSDN and other blog posts (or just press F1 when selected MapPageRoute – amazing how much effort Microsoft has put into their wonderful help system!), but here we highlighted the most common scenario for use of ASP.NET URL Routing engine. And once again, the day is saved!

blog comments powered by Disqus

Month List