The behavior of the HttpClient.PostAsync method is to dispose of the provided HttpContent object.
There are many ways to get around this behavior including constructing a new HttpContent
for each call made on the client or loading the content to a stream and changing the pointer.
I'm wondering why invoking this method automatically invokes the disposal of its IDisposable
parameters? As far as I'm aware this is not a common behavior in .NET
It's also worth noting that this behavior is observed in PUT
requests as well, which are idempotent, so the premise that this behavior is to prevent the information from being sent again doesn't seem correct.
Generally, you don't want to dispose of HttpClient unless it's used very infrequently. Regular creation and disposal may lead to socket exhaustion.
The safest, general advice would be to always dispose of the HttpResponseMessage once you have finished with using it. This does lead to a little more code noise but ensures that regardless of the internals and any future changes, your code will free/clean up unused resources such as connections as quickly as possible.
Content . It does not dispose of response. RequestMessage or the HttpRequestMessage in any other way. It, therefore, does not dispose of the HttpRequestMessage.
PostAsync(String, HttpContent) Send a POST request to the specified Uri as an asynchronous operation. PostAsync(Uri, HttpContent) Send a POST request to the specified Uri as an asynchronous operation.
I couldn't immediately find the implementation on referencesource but the WCF source contains it as well. The method you're looking for is DisposeRequestContent(HttpRequestMessage)
and the accompanying comment says this:
When a request completes,
HttpClient
disposes the request content so the user doesn't have to. This also ensures that aHttpContent
object is only sent once usingHttpClient
(similar toHttpRequestMessages
that can also be sent only once).
HttpContent content = request.Content;
if (content != null)
{
content.Dispose();
}
Basically it's a safeguard to make sure you don't send the same response twice which they consider a bad/uncommon/discouraged use case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With