Adding Base64 strings to a Url (or how I came to hate Uri.ToString())

I’ve been implementing a site that passes a Base64 encoded Ticket around in a QueryString, in my travels I noticed that the string would get encoded into the Url but the + symbols wouldn’t get converted to their Hexadecimal equivalent and hence would be Unescaped to a Space instead of +, thus busting my Base64 string. After much stuffing around with Uri.EscapeDataString, Url.HexEscape, Url.EscapeUrlString etc. I finally deducted that it was not these operations that were my problem. The culprit was a seemingly innocuous line of code in the following…

StringBuilder sb = new StringBuilder();

builder.Query = sb.ToString();
return builder.Uri.ToString();

So what’s wrong with this you ask? Well when you call Uri.ToString() it sees your + symbols encoded as %2b and decides these should really be + symbols… WHY?? They aren’t Spaces there f**ing pluses DON’T DECODE THEM!  Apparently Uri.ToString() thinks it should give an unescaped Url rather than the actual Url. So to fix this ALWAYS use  Uri.AbsoluteUri or Uri.OriginalString instead of Uri.ToString()

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: