多次调用HttpContent ReadAsAsync [英] Multiple Calls to HttpContent ReadAsAsync

查看:40
本文介绍了多次调用HttpContent ReadAsAsync的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Web API 2.2,假设我想从 HttpContent 中读取两次,每次以不同的类型读取.

Using Web API 2.2, suppose I want to read from HttpContent twice, each time as a different type.

await httpContent.LoadIntoBufferAsync(); //necessary to buffer content for multiple reads
var X = await httpContent.ReadAsAsync<T>(); //read as first type
var Y = await httpContent.ReadAsAsync<Dictionary<string, object>>(); //read as second type

当我运行上述代码时, X T 的非空实例,而 Y 为null.如果我切换顺序,则 Y 将为非空字典,而 X 将为空.换句话说,除非使用相同的泛型类型参数进行调用,否则第二次及以后对 ReadAsAsync 的调用将始终返回null.独立地,对 ReadAsAsync 的调用均按预期方式工作(即使在不必要地调用 LoadIntoBufferAsync 时也是如此).

When I run the above code, X is a non-null instance of T while Y is null. If I switch the order, Y will be a non-null dictionary while X will be null. In other words, the second and subsequent calls to ReadAsAsync will always return null unless they're called with the same generic type parameter. Independently, either call to ReadAsAsync works as expected (even when needlessly calling LoadIntoBufferAsync).

这对我来说是出乎意料的-看来我应该能够多次读取不同类型的缓冲内容.如果我添加另一行:

This is unexpected to me - it seems that I should be able to read buffered content as differing types as many times as I want. If I add another line:

var Z = await httpContent.ReadAsString();

结果是 Z 将是一个非空字符串,无论分配给 X,Y,Z 的顺序是什么.

The result is Z will be a non-null string, no matter the order of assignment to X, Y, Z.

那么这是怎么发生的,为什么我不能使用具有多种类型的 ReadAsAsync HttpContent 读取?

So how come this happens, and why can't I read from HttpContent using ReadAsAsync with multiple types?

推荐答案

文档在这个问题上很少,但是 HttpContent 像流一样,这对我来说并不奇怪,因为您可以只读一次..NET中几乎每个名称中带有"read"的方法都以这种方式起作用.

The documentation is sparse on the question, but it's not too surprising to me that HttpContent acts like a stream, in that you can read it just once. Pretty much every method in .NET with "read" in the name acts this way.

我不知道为什么多次读取相同的数据甚至每次有意义的解释都有意义,除非出于调试目的.您的榜样对我来说似乎是人为的.但是,如果您确实想这样做,可以尝试 ReadAsStreamAsync(),然后可以直接从 Stream 中读取,重置 Position 每次要再次读取它时,将属性设置为0,或者将 ReadAsByteArrayAsync()设置为0,从而为您提供一个字节数组,您可以根据需要多次读取它.

I don't have any idea why it even makes sense to read the same data multiple times, interpreting it differently each time, except possibly for debugging purposes. Your example seems contrived to me. But if you really want to do that, you can try ReadAsStreamAsync(), which you can then read from the Stream directly, resetting the Position property to 0 each time you want to read it again, or ReadAsByteArrayAsync(), giving you a byte array you can read from as many times as you like.

当然,您必须显式使用格式化程序才能将其转换为所需的类型.但这不应该成为太大的障碍.

Of course, you'll have to use the formatters explicitly to convert to the desired type. But that shouldn't be too much of an impediment.

这篇关于多次调用HttpContent ReadAsAsync的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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