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


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!