Cannot access a disposed object. ‘System.Net.Http.StringContent’ While having retry logic.

Hi,

I faced this scenario today when I was trying to make an HttpPost call using a retry logic wherein I was getting an ObjectDisposedException while trying to retry for the first time.

Exception Message:

Cannot access a disposed object. Object name: 'System.Net.Http.StringContent'

My calling code was something like this.

var httpContent = GetHttpContent();

retryPolicy.ExecuteWithRetry(async () => await httpClient.PostAsync(url, httpContent));

The problem with this code is, when the first call to PostAsync is made and it fails, the httpContent object is disposed. This is as designed in the HttpClient class. Refer the comment in this method. Although this seems odd, they intent to do this so that the user doesn’t have to do this explicitly and also to avoid the same request being Posted more than once.

So what happens is, when the first call fails, httpContent is disposed, then as we have retry mechanism, it tries to make the post call again, now with a disposed object and hence this time, the call fails with an ObjectDisposedException.

An easy way to resolve this is to NOT use a variable to store httpContent and instead, create http content directly while making the call. Something like this.

retryPolicy.ExecuteWithRetry(async () => await httpClient.PostAsync(url, GetHttpContent()));

This will make sure that every subsequent retry has a new httpContent object created.

Hope this helps!

References:

  1. http://stackoverflow.com/questions/19260060/retrying-httpclient-unsuccessful-requests
  2. http://stackoverflow.com/questions/29369945/objectdisposedexception-on-httpclient
  3. http://stackoverflow.com/a/15708633/2377928
  4. http://stackoverflow.com/a/25495500/2377928
  5. https://github.com/dotnet/corefx/blob/master/src/System.Net.Http/src/System/Net/Http/HttpClient.cs
  6. https://github.com/dotnet/corefx/issues/1794
Advertisements

About Amogh Natu

Technology enthusiast, Associate Consultant @ Microsoft, music lover, love my guitar, Microsoft.NET, ASP.NET, C#.NET Professional.
This entry was posted in General and tagged , , , , , , , , , , , , . Bookmark the permalink.

Your comments or opinions.....

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s