System.Uri.Query and the Ampersand character

February 6, 2009 09:50 by nat

I recently had a requirement to place an ampersand in a querystring as a value, now this is handled perfectly well by UrlEncoding when using the Request.QueryString() method, however, when dealing with a Uri.Query, it goes a bit wrong. When inspecting the Uri.Query value even after UrlEncoding the ampersand, %26 ("&" when UrlEncoded) has been UrlDecoded already, before you have a chance to do anything about it.

The way round this that I found is to HtmlEncode the ampersand too, so it ends up as "%26amp%3b", e.g.

string theUrl = "http://www.domain.co.uk/pagename.aspx?qskey=" + HttpUtility.UrlEncode(HttpUtility.HtmlEncode("lorem & ipsum"));

Then to grab it out of the Uri.Query value do the following

HttpUtility.HtmlDecode(this.Query.Replace("&", "%26"))

Now the querystring & delimiters show as "&"s and the encoded one as "%26".

 

 


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Related posts

Comments

September 26. 2009 09:53

I recently had a requirement to place an ampersand in a querystring as a value, now this is handled perfectly well by UrlEncoding when using the Request.QueryString() method, however, when dealing with a Uri.Query, it goes a bit wrong. When inspecting the Uri.Query value even after UrlEncoding the ampersand, %26 ("&" when UrlEncoded) has been UrlDecoded already, before you have a chance to do anything about it.

Tiffany Bracelets

October 3. 2009 07:30

Good tip! Thanks

games

Add comment


 

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

July 31. 2010 20:24

Calendar

July 2010
SuMoTuWeThFrSa
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567