I’m building an HttpClient
adapter for a connection to E*Trade. This HttpClient
requires a custom message handler that needs to know things about the connection for OAuth. Things like the access token, the consumer key, consumer secret and token secret, etc.
My configuration of this arrangement looks like this:
// Configure the E*Trade adapter.
serviceCollection
.AddHttpClient<ETradeAdapter>(httpClient => httpClient.BaseAddress = new Uri(baseAddress, UriKind.Absolute))
.AddHttpMessageHandler<ETradeMessageHandler>();
At run-time, I collect the OAuth parameters based on the user’s identity and try to plug them into the E*Trade message handler. How do I find the message adapters associated with my HttpClient
when I’m using this pattern so that I can set these parameters?
Edit: What I want to do can be accomplished with this, but it appears clumsy and I feel there just must be a better way:
var eTradeMessageHandler = this.serviceProvider.GetRequiredService<ETradeMessageHandler>();
eTradeMessageHandler.AccessToken = "some token";
eTradeMessageHandler.TokenSecret = "some secret";
var httpClient = new HttpClient(eTradeMessageHandler);
var eTradeHttpAdapter = new ETradeAdapter(httpClient);
3
You can’t without using reflection: it’s the internal _handler
field of HttpMessageInvoker
, the base class for HttpClient
.
See here the code for HttpMessageInvoker
: https://github.com/dotnet/runtime/blob/main/src/libraries/System.Net.Http/src/System/Net/Http/HttpMessageInvoker.cs
6