Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a proxy with .NET 4.5 HttpClient

I'm troubleshooting a bug with a service I call through .NET's HttpClient, trying to route the request through a local proxy (Fiddler), but my proxy settings seem to not be taking effect.

Here's how I create the client:

private HttpClient CreateHttpClient(CommandContext ctx, string sid) {     var cookies = new CookieContainer();      var handler = new HttpClientHandler {         CookieContainer = cookies,         UseCookies = true,         UseDefaultCredentials = false,         Proxy = new WebProxy("http://localhost:8888", false, new string[]{}),         UseProxy = true,     };      // snip out some irrelevant setting of authentication cookies      var client = new HttpClient(handler) {         BaseAddress = _prefServerBaseUrl,     };      client.DefaultRequestHeaders.Accept.Add(         new MediaTypeWithQualityHeaderValue("application/json"));      return client; } 

then I send the request by:

var response = CreateHttpClient(ctx, sid).PostAsJsonAsync("api/prefs/", smp).Result; 

Request goes straight to the server without attempting to hit the proxy. What did I miss?

like image 578
Mike Ruhlin Avatar asked May 13 '13 16:05

Mike Ruhlin


People also ask

What is HttpClient proxy?

Hyper Text Transfer Protocol (HTTP) is a request/response protocol between clients and servers. The HTTP client is usually a web browser. The HTTP server is a remote resource that stores HTML files, images, and other content.

What is .NET HTTP client?

Net. Http. HttpClient class sends HTTP requests and receives HTTP responses from a resource identified by a URI.

What does automatic proxy setup mean?

A proxy auto-config (PAC) file defines how web browsers and other user agents can automatically choose the appropriate proxy server (access method) for fetching a given URL.

Why does my proxy change automatically?

Some anti-virus or other software can change your proxy settings if they are set to "automatically detect", and this can cause issues.


2 Answers

This code worked for me:

var httpClientHandler = new HttpClientHandler                         {                             Proxy = new WebProxy("http://localhost:8888", false),                             UseProxy = true                         } 

Note that I am not supplying an empty array to my WebProxy constructor. Perhaps that's the problem?

like image 96
NathanAldenSr Avatar answered Sep 18 '22 05:09

NathanAldenSr


Ah, The BaseAddress I was pointing to was http://localhost:8081. Turns out that despite setting BypassOnLocal to false, evidently localhost is still special enough that it bypasses the proxy.

I added a domain binding in IIS, host file entry to point that domain to 127.0.0.1, used newly created domain, now it works.

like image 42
Mike Ruhlin Avatar answered Sep 20 '22 05:09

Mike Ruhlin