Home > Uncategorized > Simple friendly urls in ASP.Net (revisited and encapsulated)

Simple friendly urls in ASP.Net (revisited and encapsulated)

October 14, 2005

I while back I blogged about a technique we used for simple url rewriting on Channel9. The topic came up again tonight and I realized that what we did could be encapsulated into a single page with an xml file as a data source.

For the code to work properly, add the two files to your website (you’ll most likely want to rename default.aspx, unless you place the files in a subfolder). Then in IIS view the properties of the containing folder and select the Custom Errors tabs. Next set the properties of the 404 error, change the message type to url and the contents to the path leading to the aspx page.

This will cause any bad request to load up the aspx page which will then compare the bad request string to the patterns in the xml file. If a match is found, the request will then be redirected to the new url.

As an example, if I make a request for http://localhost/redirects/channel9. The redirect page will chop off of the app domain string and single out the string "channel9" which will then be used to compare to each pattern in the xml file.

A few items of note, this is just sample code so there is very little error handling, you’ll want to tighten it down before use. This covers an IIS 404 error, so any valid .aspx request will be passed to the aspnet engine and the 404 will be raised within that context, never making it to the redirect page. On Channel9, rather than redirecting, we actually add a control with properties set according to the requested url. This is great but, unfortunately cancels out postback. So you can see this code is limited in its flexibility, but can be useful for simple friendly urls.

[Download the Code]

%d bloggers like this: