Working with request body in ASP.NET Core

During API development, we might often want to read the raw request body for logging or signature validation. In case of ASP.NET Core, we could use EnableRewind() to read the request body multiple times.


using (var reader = new StreamReader(Request.Body))
{
    var body = reader.ReadToEnd();
    Request.Body.Seek(0, SeekOrigin.Begin);
}

However, if we are to use StreamReader to read the request body, we will dispose the StreamReader using the using statement. This is a mistake if we are to read the request body in the future. Hence, we should use the following way instead. The following snippet is being taken from inside a Controller.




// Read the request body, but do not dispose it
var stream = new StreamReader(httpContextAccessor.HttpContext.Request.Body);            
stream.BaseStream.Position = 0;
requestBody = await stream.ReadToEndAsync();

httpContextAccessor.HttpContext.Request.Body.Seek(0, SeekOrigin.Begin);




Comments

Popular posts from this blog

ASP.NET Core service locator pattern

Caching and generic query using NHibernate [.NET Core]