Search code examples
c#asp.net-mvc-4dotnet-httpclientsystem.net.httpwebrequest

Why is System.Net.Http HttpClient encoding my request URL?


I use the HttpClient in System.Net.Http to make requests to a web service as below:

using (var client = new HttpClient())
{
    using (var response = client.GetAsync(url).Result)
    {
        var result = response.Content.ReadAsStringAsync().Result;
    }
}

I have a sandbox application and a live application. The sandbox application has identical code (in a shared repository) which works fine, but when client.GetAsync(url).Result is called in the live application, for some reason Fiddler shows me that the requested URL has been encoded which messes the request up.

Requested URL is supposed to look like this:

/advert?paginate=1&page=1&language=en&filters[updated_at][ge]=2016-03-21%2012:19:05

But ends up looking like this:

/advert?paginate=1&page=1&language=en&filters%5Bupdated_at%5D%5Bge%5D=2016-03-21%2012:19:05

Any idea why? Thanks

N.B. Im using the Microsoft.Net.Http library from Nuget in .NET Framework 4.5


Solution

    1. Please be very specific about your question:

      • you use Microsoft.Net.Http version what?
      • you compile under .NET version what?
    2. Turned out that you compile under .NET 4.0 and this is a bug I would say, because the behavior is not identical to the .NET Fx 4.5 System.Http

    You can fix it by setting dontEscape to true in the Uri class:

     var url = new Uri(@"http://google.com/advert?paginate=1&page=1&language=en&filters[updated_at][ge]=2016-03-21%2012:19:05", dontEscape: true);