This is my personal blog. The views expressed on these pages are mine alone and not those of my employer.

Monday, 8 June 2009

WHHAAT? HttpUtility.Urlencode() doesn't encode apostrophes?

For some obscure reason HttpUtility.Urlencode() supplied with the .NET framework doesn't encode the apostrophe! The only way around this appears to be encode it, then manually replace this "special character" with %27.

This is rather worrying actually. I've used this method plenty of times, in past projects, only to have found out they can be broken with a simple '. This is a major oversight on MS's behalf (yes have you noticed the amount of apostrophe's that appear in this post?).

Anyways, looks like a quick Ctrl+F to find all instances of this I can and to replace with:

HttpUtility.UrlEncode(URL).Replace("'", "%27");

Funny how this isn't documented anywhere in the official docs isn't it?

Update:

It turns out that it isn't apostrophes that aren't encoded but the single quotation mark ( ' ).  Thanks to SuperGypo's comment below it turns out that this has now been documented by Microsoft.  In addition to letters and numbers there are several characters ignored during conversion including the single quotation mark.

However the documentation omits to explain the reason for leaving these characters out.