How to get raw request body in ASP.NET?

前端 未结 6 1132
你的背包
你的背包 2021-01-07 16:12

In the HttpApplication.BeginRequest event, how can I read the entire raw request body? When I try to read it the InputStream is of 0 length, leadin

相关标签:
6条回答
  • 2021-01-07 16:43

    I had a similar requirement to get the raw content and struck the same issue. I found that calling Seek(0, SeekOrigin.Begin) solved the problem.

    This is not a particularly good approach as it makes assumptions about how the underlying infrastructure operates, but it seems to work.

    0 讨论(0)
  • 2021-01-07 16:47

    The request object is not populated in the BeginRequest event. You need to access this object later in the event life cycle, for example Init, Load, or PreRender. Also, you might want to copy the input stream to a memory stream, so you can use seek:

    protected void Page_Load(object sender, EventArgs e)
    {
        MemoryStream memstream = new MemoryStream();
        Request.InputStream.CopyTo(memstream);
        memstream.Position = 0;
        using (StreamReader reader = new StreamReader(memstream))
        {
            string text = reader.ReadToEnd();
        }
    }
    
    0 讨论(0)
  • 2021-01-07 16:53

    Here's what I ended up doing:

    //Save the request content. (Unfortunately it can't be written to a stream directly.)
    context.Request.SaveAs(filePath, false);
    
    0 讨论(0)
  • 2021-01-07 16:58

    Pål's answer is correct, but it can be done much shorter as well:

    string req_txt;
    using (StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream))
    {
        req_txt = reader.ReadToEnd();
    }
    

    This is with .NET 4.6.

    0 讨论(0)
  • 2021-01-07 16:59

    It is important to reset position of InputStream.

    var memstream = new MemoryStream();
    Request.InputStream.CopyTo(memstream);
    Request.InputStream.Position = 0;
    using (StreamReader reader = new StreamReader(memstream)) {
        var text = reader.ReadToEnd();
        Debug.WriteLine(text);
    }
    
    0 讨论(0)
  • 2021-01-07 17:01

    In ASP.NET Core 2:

    using (var reader = new StreamReader(HttpContext.Request.Body)) {
        var body = reader.ReadToEnd();
    }
    
    0 讨论(0)
提交回复
热议问题