利用中间件记录请求的日志

时间:2021-01-28 03:55:05

话不多说,先上代码

public async Task Invoke(HttpContext context)
        {
            string headers = "";
            string body = "";
            foreach (var item in context.Request.Headers)
            {
                headers = item.Key + ":" + item.Value;
            }

            context.Request.EnableBuffering();
            StreamReader sr = new StreamReader(context.Request.Body);
            body = sr.ReadToEnd();
            context.Request.Body.Position = 0;

            _logger.LogInformation("开始请求: 路径--" + context.Request.Path
                + ",请求body:" + body + ",请求header:"
                + headers + ",query:" + context.Request.QueryString.Value);

            try
            {
                await _next.Invoke(context);
            }
            catch (System.Exception e)
            {
                _logger.LogError("请求错误:" + e.Message);

                context.Response.ContentType = "application/json";

                ResponseData<string> data = new ResponseData<string>();
                data.Code = 400;
                data.Message = e.Message;

                await context.Response.WriteAsync(JsonConvert.SerializeObject(data));
            }
            finally
            {
                
            }
        }

在实际测试中发现 StreamReader 如果放在using下或者主动Dispose,则 context.Request.Body 也会跟着释放掉导致参数为空