Creating your own URL Shrinker using ASP.Net
Sometimes sharing URLs with people via IM, Email or verbally can be a pain. Especially when email clients tend to word wrap causing your long URL to be chopped in half. Then you get a phone call from your mother complaining about how the link doesn't work (and explaining how to rebuild the URL manually is usually a hopeless effort).
The solution to this problem is simple: prevention. You need a way to shrink your URL down to a readable size so that your url mangling application doesn't find it necessary to word wrap it or so that the user can type the URL manually without too many keystrokes. You'll then prevent this annoying scenario by sending out the shrunken URL to all your happy friends and relatives.
Services like TinyURL (http://tinyurl.com) and SnipURL (http://snipurl.com) accomplish this quite well. If you want to look cool to all your friends though, you can write your own.
The logic behind it is pretty simple. Here's the high level perspective of how its implemented:
- User visits a form and enters a URL into the URL Shrinker Form
- User receives back a URL in the form of: http://mysite.com/<UID>
- User sends out his shrunken URL to all his friends
- Friend clicks on the shrunken URL
- Friend's browser asks mysite.com for the document named <UID>
- Mysite.com cannot find a document named <UID> so it hands the request off to MySite.com's custom HTTP 404 Handler
- MySite.com's custom 404 handler grabs the <UID> off the URL and fetches its associated long URL
- MySite.com sends a re-direct to the browser with the original long URL as the address
… and it all happens behind-the-scenes as far as the end-user is concerned.
There are really 3 fundamental pieces to building your own implementation. They are:
- Creating a URL Shrinker Form where the user will input their long URL
- Creating a 404 Handler/Redirect Script which will handle the URL lookup
- Configuring the Webserver to use the 404 Handler for all 404 messages
URL Shrinker Form:
The URL Shrinker form is the interface where the user will submit his long URL. I have kept my Shrink.aspx webform plain and boring for the sake of simplicity. The Shrinker webform's sole purpose is to provide the user with a means of entering the long URL into the database and feed him a shrunken URL with which he can distribute.
The URL Shrinker app is configured to use SQL Server as the database. You may choose to use another, but a code change may be required. You can change the ConnectionString value by editing the Web.config file, so the app is fairly flexible.

(Shrink.aspx design view)
Dumping the URL into the database is simple. I've created a Utility class that will aid in the storage and retrieval of the URLs. Its simply a matter of fetching the URL value from the Textbox control and calling Utils.AddURL(). I've included some checks to help make sure the input is ok. You may wish to add more checks:
private void btnShrink_Click(object sender, System.EventArgs e)
{
try
{
if ((!txtURL.Text.ToLower().StartsWith("http://")) && (!txtURL.Text.ToLower().StartsWith("ftp://")))
{
txtURL.Text = "http://" + txtURL.Text;
}
Uri uri = new Uri(txtURL.Text, false);
string id = Utils.AddURL(ConfigurationSettings.AppSettings["ConnectionString"], txtURL.Text);
lbLink.Text = ConfigurationSettings.AppSettings["WEBROOT"] + id;
lbLink.NavigateUrl = lbLink.Text;
lbError.Text = "";
}
catch (System.UriFormatException err)
{
lbError.Text = "Invalid URL Format:\r\n";
lbError.Text += txtURL.Text;
}
}
Creating a 404 Handler/Redirect Script
Now that we've gotten our data into the database, received the associated ID and displayed the shrunk'd URL to the user, we need to write some code to handle navigations properly.
The shrunken URL navigation is handled by the 404Handler.aspx webform. If you haven't figured out why its named the way it is, you'll find out in the next section.
The purpose of the 404Handler.aspx is to lookup the URL that the browser is requesting (in the form: http://mysite.com/<UID>) and extract the URL ID, then using that ID, find its associated long URL in the database and send the browser a redirect to the long URL:
private void Page_Load(object sender, System.EventArgs e)
{
try
{
// We receive the original URL in the form of: "404;<URL>"
// so chop off the "404;"
// Then construct a URI object to ease in parsing.
System.Uri uri = new System.Uri(Request.QueryString[0].Substring(4));
if (uri.LocalPath.Length > 1)
{
// Get the URL ID. It should be the only contents of the the LocalPath // in the URI. Using the URL ID, get the long URL from the database.
Response.Redirect(Utils.GetURL(ConfigurationSettings.AppSettings["ConnectionString"], uri.LocalPath.Replace("/", "")), true);
}
}
catch (Exception err)
{
// swallow the exception
}
// If we haven't already returned, then we should redirect
// the browser to the real 404 page.
Response.Redirect(ConfigurationSettings.AppSettings["REAL_404_PAGE"], true);
}
Webserver Configuration:
Since deploying the application to IIS is beyond the scope of this document (although it isn't hard), I'll cut to the chase and assume you've already deployed your URLShrinker application to /URLShrinker.
Before we want IIS to hand the 404Handler.aspx webform requests from the browser, we want IIS to first check to see if the request is for a valid local file. The simplest way of doing this is to set our application as a custom 404 handler as outlined in the description above. As a custom 404 handler, we're (virtually) guarenteed two things:
- The local file for the URL does not exist
- We'll receive the original request URL in the QueryString with which we extract the URL ID
To configure the 404Handler.aspx as the default 404 handler for your website, you'll have to open the IIS applet:
Start -> Control Panel -> Administrative Tools -> Internet Information Services
Then choose the website where your app is deployed, right click and select Properties:

(IIS Configuration Applet)
Select the Custom Errors tab and scroll to the 404 entry and click "Edit Properties"

(IIS Website Properties form)
Change the Message Type to URL and put in the relative path to the 404Handler.aspx:

That’s it. You may need to restart IIS for changes to take effect.
URL Shrinker in action
So lets say you want to send your Mom some information about Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch, a small town off the coast of Wales whose unofficial website is: http://www.llanfairpwllgwyngyllgogerychwyrndrobwyll-llantysiliogogogoch.com/. Since this name is clearly too long, we will shrink it at the following page: http://dev.kzgrey.com/URLShrinker/Shrink.aspx. Paste in the long URL and you end up with a shrunken URL of: http://dev.kzgrey.com/1. This is clearly more managable than the original URL.
Project Source
The source for this project is available at: http://dev.kzgrey.com/src/
Disclaimer:
This posting is provided "AS IS" with no warranties, and confers no rights.
Use of included script samples are subject to the terms specified at http://www.microsoft.com/info/cpyright.htm