[英]MemoryStream from HttpContent without copying
I m trying to use System.Net.Http for POST requests.我正在尝试将 System.Net.Http 用于 POST 请求。 I m ok with HTTP response body being in memory but need to obtain MemoryStream for it.我对内存中的 HTTP 响应主体感到满意,但需要为其获取 MemoryStream。 One way to do that would be to call HttpContent.GetAsByteArrayAsync() and wrap a MemoryStream on top of it, but I think this would require content to be copied into a separate byte array (since it returns Task of byte[]).一种方法是调用 HttpContent.GetAsByteArrayAsync() 并在其上包装一个 MemoryStream,但我认为这需要将内容复制到单独的字节数组中(因为它返回字节 [] 的任务)。
If the response body is already in some internal buffer in HttpContent, is it possible to create MemoryStream on top of that buffer, or return MemoryStream from HttpContent somehow and avoid copying to a separate byte array?如果响应主体已经在 HttpContent 的某个内部缓冲区中,是否可以在该缓冲区之上创建 MemoryStream,或者以某种方式从 HttpContent 返回 MemoryStream 并避免复制到单独的字节数组?
There is also HttpContent.GetAsStreamAsync(), but that returns regular Stream, not MemoryStream.还有 HttpContent.GetAsStreamAsync(),但它返回常规 Stream,而不是 MemoryStream。 Even though it is probably an instance of MemoryStream already, I suppose it is not safe or a good practice to cast the returned stream to MemoryStream?即使它可能已经是 MemoryStream 的一个实例,我认为将返回的流转换为 MemoryStream 是不安全的或不是一个好的做法? (since this is implementation detail that could change). (因为这是可能会更改的实现细节)。
Is there any other way of doing this, or do i have no choice but to copy into byte[] first?有没有其他方法可以做到这一点,或者我别无选择,只能先复制到 byte[] 中?
Thanks.谢谢。
If you call LoadIntoBufferAsync
first, ReadAsStreamAsync
returns a readonly MemoryStream
:如果您先调用LoadIntoBufferAsync
, ReadAsStreamAsync
将返回只读MemoryStream
:
await req.Content.LoadIntoBufferAsync();
var stream = (MemoryStream) await req.Content.ReadAsStreamAsync();
If you call LoadIntoBufferAsync
first, CopyToAsync
can be used to populate a readonly MemoryStream
:如果您先调用LoadIntoBufferAsync
,则CopyToAsync
可用于填充只读MemoryStream
:
var stream = new MemoryStream(req.Content.Headers.ContentLength);
await req.Content.LoadIntoBufferAsync((int)req.Content.Headers.ContentLength);
await req.Content.CopyToAsync(stream);
This implementation doesn't depend on side effects and is supported by the docs in all framework versions: https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpcontent.loadintobufferasync?view=netframework-4.6.2此实现不依赖于副作用,并受所有框架版本中的文档支持: https : //docs.microsoft.com/en-us/dotnet/api/system.net.http.httpcontent.loadintobufferasync?view=网络框架-4.6.2
Note: I tried to edit the above answer, but couldn't do it... So here you are.注意:我试图编辑上面的答案,但无法做到......所以你来了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.