问题描述
对象。
The behavior of the HttpClient.PostAsync method is to dispose of the provided HttpContent object.
有很多方法可以解决此问题,包括构造一个新的 HttpContent
对于在客户端上进行的每个调用或将内容加载到流中并更改指针。
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.
我想知道为什么方法会自动调用其 IDisposable
参数的处置?据我所知,这不是.NET中的常见行为。
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
还值得注意的是,这种行为在 PUT中可见
请求也是幂等的,因此,这种行为是防止再次发送信息的前提似乎并不正确。
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.
推荐答案
我无法立即在referencesource上找到实现,但是WCF源也包含它。您正在寻找的方法是和附带的注释说:
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:
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.
这篇关于为什么HttpClient.PostAsync和PutAsync处置内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!