gpt4 book ai didi

c# - 为什么我不能两次读取 Http Request Input 流?

转载 作者:IT王子 更新时间:2023-10-29 04:48:42 27 4
gpt4 key购买 nike

我正在放入一些调试代码来测试一些东西,然后调试代码没有按预期运行。下面的示例是演示我的问题的简化代码。

这是在 .NET 4 中使用 WebApi,我试图在调试代码中打印出 http 请求的主体。为此,我寻找输入流并读取流。第一次它工作正常,但如果我再次尝试读取它,我得到一个空字符串。

为什么我不能回头读取 InputStream 第二次?在下面的示例中,body2 始终为空。在第二组中,CanSeek 仍然为真,第二次调用 ReadToEnd() 返回一个覆盖默认值的空字符串。

using System.IO;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;

public class TestController : ApiController
{

public class TestOutuput
{
public string firstRead;
public string secondRead;
}

public HttpResponseMessage Post()
{
string body1 = "default for one";
string body2 = "default for two";
if (HttpContext.Current.Request.InputStream.CanSeek)
{
HttpContext.Current.Request.InputStream.Seek(0, System.IO.SeekOrigin.Begin);
}
using (var reader = new StreamReader(HttpContext.Current.Request.InputStream))
{
body1 = reader.ReadToEnd();
}

if (HttpContext.Current.Request.InputStream.CanSeek)
{
HttpContext.Current.Request.InputStream.Seek(0, System.IO.SeekOrigin.Begin);
}
using (var reader2 = new StreamReader(HttpContext.Current.Request.InputStream))
{
// this is always empty, even after seek back to origin
body2 = reader2.ReadToEnd();
}

TestOutuput testOutput = new TestOutuput() { firstRead = body1, secondRead = body2 };
HttpResponseMessage response = new HttpResponseMessage();
return Request.CreateResponse<TestOutuput>(HttpStatusCode.OK, testOutput);
}
}

最佳答案

StreamReader 在释放时调用给定流上的 Dispose。要使流保持打开状态,请使用 appropriate constructor对于 StreamReader。或者更好的是,只需将其复制到缓冲区。来自 MSDN:

When reading from a Stream, it is more efficient to use a buffer that is the same size as the internal buffer of the stream.

参见 this question例如。

关于c# - 为什么我不能两次读取 Http Request Input 流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21971467/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com