WP7 URI’s need to be encoded just like on the web

I found a little gotcha with the way WP7 handles the encoding of uri’s which could trip you up when passing string values through to pages via query strings.

I was trying to pass this ID through to a second page via a parameter on the uri.

var id = “HxmyKn0F+Y8XbksplmTzFQ==”;
NavigationContext.Navigate(new Uri(“MyPage.xaml?id=” + id, UriKind.Relative));

Only thing is, when I pulled the value out of the QueryStrings collection the ID had changed to:

“HxmyKn0F Y8XbksplmTzFQ==”

Silverlight had changed the “+” sign into a space.  But why?

Although it is a little counter intuitive in this context, this actually is the expected behaviour.  The spec for URL encoding (RFC 1738 if you feel the urge to read up) attaches special significance to the “+” sign as part of the URL (along with other special characters – see below).  We can’t include these characters in our data so we need to escape it as described in the spec.

Obviously this is nothing new.  It is one of the first things you learn when you start developing for the web.  In fact we can use the same HttpUtility.UrlEncode() utility that we would on the web. 

var encodedUri = “/MySecondPage.xaml?myID=” + HttpUtility.UrlEncode(“HxmyKn0F+Y8XbksplmTzFQ==”); 

Lesson: Unless you can absolutely guarantee that your string parameters won’t contain reserved URL characters, they must be encoded using UrlEncode() first.  This is actually quite important and is often left out of most tutorials about navigation on Windows Phone7.

For the record here is a list of the all of the reserved characters:

$ ? }
& @ |
, < ^
/ > ~
: # [
; % ]
= { `

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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