来自 HttpContent 的 MemoryStream,无需复制

Yev*_*y P 2 c# post system.net http .net-core

我正在尝试使用 System.Net.Http 进行 POST 请求。我同意 HTTP 响应主体位于内存中,但需要为其获取 MemoryStream。一种方法是调用 HttpContent.GetAsByteArrayAsync() 并在其上包装 MemoryStream,但我认为这需要将内容复制到单独的字节数组中(因为它返回 byte[] 的任务)。

如果响应正文已经位于 HttpContent 中的某个内部缓冲区中,是否可以在该缓冲区顶部创建 MemoryStream,或者以某种方式从 HttpContent 返回 MemoryStream 并避免复制到单独的字节数组?

还有 HttpContent.GetAsStreamAsync(),但它返回常规 Stream,而不是 MemoryStream。尽管它可能已经是 MemoryStream 的一个实例,但我认为将返回的流转换为 MemoryStream 并不安全,也不是一个好的做法?(因为这是可能改变的实现细节)。

有没有其他方法可以做到这一点,或者我别无选择,只能先复制到 byte[] 中?

谢谢。

wei*_*hch 7

如果您LoadIntoBufferAsync先调用,ReadAsStreamAsync则返回readonly MemoryStream

await req.Content.LoadIntoBufferAsync();
var stream = (MemoryStream) await req.Content.ReadAsStreamAsync();
Run Code Online (Sandbox Code Playgroud)