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?

3 comments:

  1. I think you've put the apostrophe in the word apostrophes unnecessarily as it is just a pluralisation.

    Sorry...
    ReplyDelete
  2. True, I'll change it now. Thanks
    ReplyDelete
  3. This is a dumb bug that had me for a loop for awhile. Thanks for the post. I figured after a bunch of testing that I would have to replace the apostrophe, but wanted to see if anyone else experienced first.
    ReplyDelete