On a small test website I’m building in my spare time, I wanted a way to count the number of clicks to the outgoing links from that site. Imaging hosting banners or other affiliate links where you get paid per click, it would be nice to know how many have clicked on them instead of relying on the advertiser’s own statistics. There are third-party products that can do it, but I would like to keep that data myself and it would be fun to build at the same time.
I came up with a very simple solution that uses a generic handler called redirect.ashx. The handler registers the clicks in an XML file and is also able to print out the stats in a nice looking table. It works by linking to redirect.ashx?url=http://example.com instead of http://example.com.
To get the stats from the handler, call it with the stats parameter redirect.ashx?stats=true. That prints out a table with the statistics from each redirected URL.
Crawlers and spiders
To avoid that the clicks made by crawlers and spiders, you can use this simple little trick that filters them out.
<a href="http://example.com" onclick="if(this.href.indexOf('redirect.ashx')==-1)this.href='redirect.ashx?url='+this.href">Click here</a>
Download the redirect.ashx handler below and put it somewhere in your web project. If your website doesn’t already have an App_Code folder in the root, then add it. That’s all you need to do. The handler automatically adds an XML file in the App_Code folder the first time it is hit and it automatically creates an XML node for every new URL it redirects.