6
votes

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");
}
1
var handler = client.GetType().BaseType.GetField("handler", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(client) as HttpClientHandler;Jimi
Thanks Jimi, this is exactly what I was trying to achieve - works a treat! Learnt something for the future too!cty

1 Answers

0
votes

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.