为什么HttpClient.PostAsync和PutAsync处置内容? [英] Why do HttpClient.PostAsync and PutAsync dispose the content?

查看:134
本文介绍了为什么HttpClient.PostAsync和PutAsync处置内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HttpClient.PostAsync 方法是处理提供的 HttpContent 对象。

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源也包含它。您正在寻找的方法是 DisposeRequestContent(HttpRequestMessage) 和附带的注释说:

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:


请求完成后, HttpClient 处置请求内容,因此用户不必这样做。
这还确保了 HttpContent 对象仅使用 HttpClient 发送一次(类似于 HttpRequestMessages ,也只能发送一次)。

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.

这篇关于为什么HttpClient.PostAsync和PutAsync处置内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆