Literal ampersands in System.Uri query string
- by Nathan Baulch
I'm working on a client app that uses a restful service to look up companies by name.
It's important that I'm able to include literal ampersands in my queries since this character is quite common in company names.
However whenever I pass %26 (the URI escaped ampersand character) to System.Uri, it converts it back to a regular ampersand character! On closer inspection, the only two characters that aren't converted back are hash (%23) and percent (%25).
Lets say I want to search for a company named "Pierce & Pierce":
var endPoint = "http://localhost/companies?where=Name eq '{0}'";
var name = "Pierce & Pierce";
Console.WriteLine(new Uri(string.Format(endPoint, name)));
Console.WriteLine(new Uri(string.Format(endPoint, Uri.EscapeUriString(name))));
Console.WriteLine(new Uri(string.Format(endPoint, Uri.EscapeDataString(name))));
All three of the above combinations return:
http://localhost/companies?where=Name eq 'Pierce & Pierce'
This causes errors on the server side since the ampersand is (correctly) interpreted as a query arg delimiter. What I really need it to return is the original string:
http://localhost/companies?where=Name eq 'Pierce %26 Pierce'
How can I work around this behavior without discarding System.Uri entirely?
I can't replace all ampersands with %26 at the last moment because there will usually be multiple query args involved and I don't want to destroy their delimiters.
Note: A similar problem was discussed in this question but I'm specifically referring to System.Uri.