Wednesday, 4 August 2010

Getting parameters from RawUrl

Most of the sites I'm working on use URL re-writing (URLRW for short), or "vanity/friendly URLs" as some SEO bods call them. Also, most of the sites I'm working on have affiliate schemes and PPC schemes sending traffic to the sites.

The URLRW rules turn the provided Url into one with appended parameters to identify specfic content. For example:

Vanity Url displayed in browser:
Url after rewriting:
Picking up the parameters in .Net is easy:

Things get a bit more complex when parameters need to be appended to the vanity Url and recognised by your code. PPC traffic to your yellow widgets might be sent to:
This Url is re-written by your URLRW rules, and so you can't grab the utm_x parameters using Request.QueryString["utm_x"]. We can however access the 'unfriendly' Url using
which using the above example will give us the string
but grabbing the parameter values with ease doesn't seem quite so obvious. We could write some kind of bespoke method to parse through the string to find our params and value. The good news is we don't have to. Using the following code you can take the 'real' or 'unfriendly' Url string, and grab the parameter values with ease:
Uri theRealURL = new Uri(HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.RawUrl);

string utm_source = HttpUtility.ParseQueryString(theRealURL.Query).Get("utm_source");

string utm_medium = HttpUtility.ParseQueryString(theRealURL.Query).Get("utm_medium");

string utm_campaign = HttpUtility.ParseQueryString(theRealURL.Query).Get("utm_campaign");

1 comment:

Comments are moderated, so you'll have to wait a little bit before they appear!