I would like to log incoming requests with method, path, body and other information. My problem is that after logging what I need the controller get only a null variable as the method parameter. I'm using .net core 1.1, IIoggerFactory, Serilog extension, and the following middleware method:
public async Task Invoke(HttpContext context)
{
StringValues sessionId;
var session = string.Empty;
if (context.Request.Headers.TryGetValue("X-SessionID", out sessionId))
{
session = sessionId.FirstOrDefault();
if (session != null)
{
var requestBodyStream = new MemoryStream();
var originalRequestBody = context.Request.Body;
await context.Request.Body.CopyToAsync(requestBodyStream);
requestBodyStream.Seek(0, SeekOrigin.Begin);
var url = UriHelper.GetDisplayUrl(context.Request);
var requestBodyText = new StreamReader(requestBodyStream).ReadToEnd();
_logger.LogDebug($"{session} {context.Request.Method} {url} {requestBodyText}");
requestBodyStream.Seek(0, SeekOrigin.Begin);
context.Request.Body = requestBodyStream;
await _next(context);
context.Request.Body = originalRequestBody;
}
}
await _next(context);
}
How can I log the requests and keep the request body for the controller after the middleware?