I recently upgraded an API to .NET Core 3, and as far as I can tell, this bit stopped working after the upgrade.
I want to log exceptions AND the json payload that was passed in via the request body. This ExceptionLogger is plugged in as a filter to handle errors globally:
public class ExceptionLogger
{
private readonly IServiceScopeFactory _factory;
public ExceptionLogger(IServiceScopeFactory factory)
{
_factory = factory;
}
public async Task<Guid?> LogException(Exception ex)
{
using var scope = _factory.CreateScope();
var accessor = scope.ServiceProvider.GetRequiredService<IHttpContextAccessor>();
var displayUrl = accessor?.HttpContext?.Request?.GetDisplayUrl();
var payload = await RetrievePayload(accessor, displayUrl);
// ... code proceeds to log the exception, including the payload.
}
private async Task<string> RetrievePayload(IHttpContextAccessor accessor, string displayUrl)
{
accessor.HttpContext.Request.EnableBuffering();
accessor.HttpContext.Request.Body.Seek(0, System.IO.SeekOrigin.Begin);
using var sr = new System.IO.StreamReader(accessor.HttpContext.Request.Body);
return await sr.ReadToEndAsync(); // The request body is always empty now....!
}
}
The accessor
has querystring and form parameters, and even the accessor.HttpContext.Request.ContentLength
has a value indicating the payload was there. However, the Request.Body
stream is empty, even after I reset the cursor position.
How can I get the request body at this point?