10

When working with a HttpClient instance and HttpClientHandler instance (.Net Framework, not using Core), is it possible to access the HttpClientHandler instance/its properties later in any way (for read-only purposes)?

Unfortunately creating the HttpClientHandler instance as a variable for referencing later isnt possible as the HttpClient instance is being passed to a library as a param and we cannot change calling client.

For example, I would like to achieve something like so:

// Created in client we cant modify   
var client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = True, PreAuthenticate = True });

// Class we can modify
public void DoSomething(HttpClient client)
{
    if (client.HttpClientHandler.UseDefaultCredentials == True) Console.WriteLine("UseDefaultCredentials: True");
}
cty
  • 357
  • 5
  • 16
  • 3
    `var handler = client.GetType().BaseType.GetField("handler", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(client) as HttpClientHandler;` – Jimi Jul 20 '20 at 19:34
  • Thanks Jimi, this is exactly what I was trying to achieve - works a treat! Learnt something for the future too! – cty Jul 21 '20 at 13:37

1 Answers1

-1

Let me re-edit my answer. Using the constructor

public class MyClass {
  private readonly HttpClientHander _handler;
  private readonly HttpClient _client;

  public MyClass() {
     _handler = new HttpClientHander() { /* Initialize the properties */ }
     _client = new HttpClient(_handler);
  }

  public void MyMethod() {
    if (_handler.TheProperty == true;) // Do something
  }
}

I hope this makes sense. I'm sure it works because of the way objects are referrenced.

  • Unfortunately I cant do that, we cant modify the client which is passing a HttpClient instance into our class as a param. We can only work with the passed instance in our method DoSomething(HttpClient client) { ... } – cty Jul 20 '20 at 19:26
  • I have re-edited my answer, try it and see if it works – developerharon Jul 20 '20 at 19:46
  • Thank you for the suggestion, this would work if we could make changes to this degree, but unfortunately we cant at this moment. Jimi's suggestion will work for our current scenario as it allows us keep everything the same and just access the handler via the HttpClient instance coming through the param. Thanks again! – cty Jul 21 '20 at 13:36