I need to consume a service that takes a GET parameter named “names[]”.
For example: GET http://example.com/name2id?names[]=john
When I try to consume that in C# using a WebClient, the brackets gets encoded to %5B%5D, which the servies does not understand. When I send the above using my browser (un-encoded), everything works fine.
Heres the example that does not work:
using (var client = new System.Net.WebClient())
{
response = client.DownloadString(new Uri("http://example.com/name2id?names[]=john"));
}
Monitored by fiddler, heres the request:
GET http://example.com/name2id?names%5B%5D=john HTTP/1.1
Host: example.com
Connection: Keep-Alive
Is there any way to make the framework NOT encode the URL, or some other way around this issue?
P.S. I do not control the API so I cannot change that.
UPDATE:
This is kinda wierd. I found a solution, changing my C# code to:
using (var client = new System.Net.WebClient())
{
response = client.DownloadString(new Uri("http://example.com/name2id?names[]=john", true));
}
Note the boolean dontEscape in Uri. It is actually deprecated, but it works? Can anyone explain this?
As mentioned by CodeInChaos, the URL is not valid according to RFC2396.
To make C# not escape invalid characters, the overloaded method of URI can be usen:
However, this method is deprecated but apparently it still works. I have to live with the warning popping up 🙂