Friendly URL Rewriting in ASP.NET

This article demonstrates a how to create friendly URLs for user content in ASP.net applications. The examples below are in C#. Convert them to VB if that’s your language of choice.

Background

Sites like Twitter provide users with a direct link to their content in the format of "http://twitter.com/username“.

Supplying a simple URL to enable users to share their content is integral to the success of any social networking site and can be beneficial in many other applications.

The following two example solutions demonstrate how to achieve this using 1) ASP.net alone and 2) an ISAPI filter with slightly less overhead.

So let’s start with an example. Currently, your users visit their profiles by visiting http://www.site.com/Profile.aspx?u=myusername. You want to make life simpler for them remove the ugly query string values and references to the ASPX page (e.g. http://www.site.com/users/myusername)

There are two ways this can be achieved:

Solution #1

Place the following code in the Global.asax within your project. You will then have to tell IIS that ASP.net will handle all requests (not just aspx requests).

 ' Global.asax Variable
private System.Text.RegularExpressions.Regex rxUserURI;
' Add to Application Start event
rxUserURI = new Regex("

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.