微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 为什么我无法读取Http请求输入流两次?

我正在加入一些调试代码来测试一些事情,然后调试代码的行为不如预期.下面的示例是一个简化的代码来演示我的问题.

这是在.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.要使流打开使用StreamReader的 appropriate constructor.
或者更好的是,只需将其复制到缓冲区.从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.

原文地址:https://www.jb51.cc/csharp/94756.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐