Why do HttpClient.PostAsync and PutAsync dispose the content?

。_饼干妹妹 提交于 2019-12-19 03:21:53

问题


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.


回答1:


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 a HttpContent object is only sent once using HttpClient (similar to HttpRequestMessages 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.



来源:https://stackoverflow.com/questions/25495394/why-do-httpclient-postasync-and-putasync-dispose-the-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!