相关疑难解决方法(0)

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

我正在添加一些调试代码来测试一些东西,然后调试代码没有按预期运行.以下示例是用于演示我的问题的简化代码.

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

为什么我不能再次寻找并读取InputStream?在下面的示例中,body2始终为空.在第二组中,CanSeek仍为true,第二次调用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 …
Run Code Online (Sandbox Code Playgroud)

.net c# asp.net-mvc asp.net-web-api

19
推荐指数
2
解决办法
3万
查看次数

标签 统计

.net ×1

asp.net-mvc ×1

asp.net-web-api ×1

c# ×1