Literal ampersands in System.Uri query string

Posted by Nathan Baulch on Stack Overflow See other posts from Stack Overflow or by Nathan Baulch
Published on 2010-05-20T09:22:31Z Indexed on 2010/05/20 9:30 UTC
Read the original article Hit count: 338

Filed under:
|
|
|
|

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.

© Stack Overflow or respective owner

Related posts about .NET

Related posts about escaping