asp.net核心mvc日志请求正文

时间:2017-09-22 09:59:29

标签: c# asp.net-mvc asp.net-core

我想用方法,路径,正文和其他信息记录传入的请求。我的问题是,在记录我需要的内容后,控制器只获取一个null变量作为方法参数。我使用.net核心1.1,IIoggerFactory,Serilog扩展和以下中间件方法:

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);
    }

如何在中间件之后记录请求并保留控制器的请求体?

1 个答案:

答案 0 :(得分:0)

记录传入请求的解决方案很好我只是忘记了方法结束时的其他内容。工作代码:

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.LogInformation($"{session} {context.Request.Method} {url} {requestBodyText}");

                requestBodyStream.Seek(0, SeekOrigin.Begin);
                context.Request.Body = requestBodyStream;

                await _next.Invoke(context);
                context.Request.Body = originalRequestBody;
            }
        } else {
            await _next.Invoke(context);
        }
    }