0

I have a class that wraps a DI'ed HttpClient and has some standard function that employ the use of Polly. I would inherit classes from this HttpClientEx class and utilize its common functionality in my other code.

Recently a requirement came up that our messages to/from httpclient should be logged. I added an HttpMessageHandler that implemented some common logging functionality but now I have a problem:

When I invoke any of my Gets/Posts etc. using Polly:

await polPolly.ExecuteAsync(async(ctCancelToken)=>
{
        return await HttpClient.GetAsync(sUrl, ctCancelToken);
}, CancellationToken.None);

It throws the exception: Cannot access a disposed object. Object name: 'System.Net.Http.HttpConnection+HttpConnectionResponseContent'

I've read online that this could be because I'm not making my message handler "re-usable" and that Polly is causing this to be disposed causing this problem. All the examples I see out there for HttpMessageHandlers that address this show new HttpClient(SomeMessageHandler, false) as the "fix"... BUT: This isn't a fix. You aren't even supposed to use HttpClient in this fashion. It is supposed to be DI'ed...

So the question is: How do I specify my handler is reusable in a way that complies with the proper way to use HttpClient? I'm open to using IHttpClientFactory or Typed HttpClients... Either will do. I can't seem to find a way to configure this property.

Thanks!

James

ArunPratap
  • 4,816
  • 7
  • 25
  • 43
James Scott
  • 990
  • 2
  • 10
  • 29
  • 1
    IHttpClientFactory certainly manages HttpClient handler lifetimes and handler disposal correctly for you. Polly does not dispose Http message handlers or content (it does not dispose any object it does not own). The exception reads like it is telling you the HttpContent in the response has been disposed. Notes [here](https://stackoverflow.com/questions/19260060/retrying-httpclient-unsuccessful-requests) and [here](https://www.stevejgordon.co.uk/demystifying-httpclient-internals-httpresponsemessage) around HttpResponse content disposal may be useful. – mountain traveller Nov 20 '19 at 08:21
  • 1
    IHttpClientFactory also by default configures its own [LoggingHttpMessageHandler](https://github.com/aspnet/Extensions/blob/9112c85ab65b9114f05c4cd0a9c592c077436aee/src/HttpClientFactory/Http/src/Logging/LoggingHttpMessageHandler.cs) for you - another possible reason to switch (depending on your logging needs - you can also easily configure in your own custom handlers with HttpClientFactory) – mountain traveller Nov 20 '19 at 20:10

1 Answers1

0

@mountain traveller - That was it. I was disposing my HttpResponseMessage within my custom handler. I should not have been.

Thanks for the info.

James Scott
  • 990
  • 2
  • 10
  • 29