public async Task Invoke(HttpContext context)
        {
            try
            {
                visitLog = new VisitLog();
                var request = context.Request;
                visitLog.RemoteIpAddress = context.Connection.RemoteIpAddress?.ToString();
                visitLog.Url             = request.Path.ToString() + context.Request.QueryString.Value;
                visitLog.Headers         = request.Headers.ToDictionary(k => k.Key, v => string.Join(";", v.Value.ToList()));
                visitLog.Method          = request.Method;
                visitLog.ExcuteStartTime = DateTime.Now;
                context.Request.EnableRewind();
                var encoding = GetEncoding(request.ContentType);
                await ReadRequestBodyAsync(context.Request.Body, encoding);

                _logger.LogInformation(visitLog.ToString());
                if (context.Request != null && context.Request.Path != null && !context.Request.Path.Value.Contains("swagger"))
                {
                    EnableReadAsync(context.Response);
                    context.Response.OnCompleted(async o =>
                    {
                        if (o is HttpContext c)
                        {
                            await ReadBodyAsync(c.Response).ConfigureAwait(false);
                        }
                    }, context);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "记录请求内容时出错");
            }
            finally
            {
                await _next.Invoke(context);
            }
        }
Ejemplo n.º 2
0
 private Task ResponseCompletedCallback(object obj)
 {
     visitLog.ExcuteEndTime = DateTime.Now;
     logger.LogInformation($"VisitLog: {visitLog.ToString()}");
     return(Task.FromResult(0));
 }