Search code examples
c#asp.net-corestreamreaderhttpcontext

How to get HttpRequest body in .net core?


I want to get Http Request body in .net core , I used this code:

using (var reader
    = new StreamReader(req.Body, Encoding.UTF8))
{
    bodyStr = reader.ReadToEnd();
}
req.Body.Position = 0

But I got this error:

System.ObjectDisposedException: Cannot access a disposed object. Object name: 'FileBufferingReadStream'.

An error occurs after the using statement of the line

How to get HttpRequest Body in .net core? and how to fix this error?


Solution

  • use this extension method to get httpRequest Body:

       public static string GetRawBodyString(this HttpContext httpContext, Encoding encoding)
        {
            var body = "";
            if (httpContext.Request.ContentLength == null || !(httpContext.Request.ContentLength > 0) ||
                !httpContext.Request.Body.CanSeek) return body;
            httpContext.Request.EnableRewind();
            httpContext.Request.Body.Seek(0, SeekOrigin.Begin);
            using (var reader = new StreamReader(httpContext.Request.Body, encoding, true, 1024, true))
            {
                body = reader.ReadToEnd();
            }
            httpContext.Request.Body.Position = 0;
            return body;
        }
    

    The important thing is that HttpRequest.Body is a Stream type And when the StreamReader is disposed, HttpRequest.Body is also disposed.

    I had this problem until I found the below link in GitHub: Refer to the below link and the GetBody method https://github.com/devdigital/IdentityServer4TestServer/blob/3eaf72f9e1f7086b5cfacb5ecc8b1854ad3c496c/Source/IdentityServer4TestServer/Token/TokenCreationMiddleware.cs