3

In my C# application I'm trying to send an HTTP request to an external company outside of our firewall. When I use the below code, I'm getting back an error that the remote site has forcibly closed the connection. I'm assuming I'm doing something incorrectly with the proxy setting but I'm not sure what. Our proxy does not require authentication.

var content = new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json");

using (var handler = new HttpClientHandler()) {
    handler.Proxy = new WebProxy("http://proxy.my.domain.com:911");

    using (var client = new HttpClient(handler: handler, disposeHandler: false)) {
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "...");

        var response = await client.PostAsync($"https://...", content);

I've printed out the encoded JSON that gets sent and if I just do things manually via curl the request goes right though, so I'm sure that my URL, bearer token and JSON are all correct.

Grzegorz Smulko
  • 1,740
  • 15
  • 33
Gargoyle
  • 7,401
  • 10
  • 55
  • 99

1 Answers1

1

As it is mentioned in the comments, the proxy variable must be set to true. I would like to emphasize it for other users having the same problem.

As this is mentioned in the docs.

I give a small example of how to use it in a factory like class:

private HttpClient ClientFactoryV02()
{
    var clientHandler = new HttpClientHandler(){ UseProxy = true};
    clientHandler.Proxy = new WebProxy("address-of-proxy");

    var client = new HttpClient(clientHandler)
    {
        BaseAddress = new Uri("uri");
    }
}
_createHttpClient = () => ClientFactoryV02();

Credits to: ZagNut, Ben.

GingerHead
  • 7,882
  • 14
  • 54
  • 91