我正在尝试(但失败)从 Request.HttpContent 对象中获取实际的 JSON 字符串。
这就是我正在做的事情:
private async Task<string> GetRequestBodyAsString(HttpContent content)
{
string result;
using (var streamCopy = new MemoryStream())
{
await content.CopyToAsync(streamCopy);
streamCopy.Position = 0;
result = new StreamReader(streamCopy).ReadToEnd();
}
return result;
}
我的问题是,在执行此代码时,我总是得到一个空字符串——除非我在将 streamCopy 位置设置为零的行上使用断点,这让我认为代码在启动 CopyToAsync 方法后继续执行.
如果我将其更改为:
using (var streamCopy = new MemoryStream())
{
do
{
count++;
await content.CopyToAsync(streamCopy);
} while (streamCopy.Length == 0);
streamCopy.Position = 0;
result = new StreamReader(streamCopy).ReadToEnd();
}
它总是能正常工作(例如,结果将包含 JSON,但这闻起来……很臭。
我在这里做错了什么?