コード例 #1
0
        private (Stream, string) Preprocess(HttpContext context, LinkedBuffer response, LinkedBuffer request)
        {
            var originalRequestBody = new StreamReader(context.Request.Body).ReadToEnd();
            var bytesToWrite        = Encoding.UTF8.GetBytes(originalRequestBody);

            request.Write(bytesToWrite, 0, bytesToWrite.Length);
            request.Seek(0, SeekOrigin.Begin);
            context.Request.Body = request;
            var originalResponseBody = context.Response.Body;

            context.Response.Body = response;
            return(originalResponseBody, originalRequestBody);
        }
コード例 #2
0
        private async Task Postprocess(HttpContext context, LinkedBuffer response, string originalRequestBody, ILogger <HttpLoggingMiddleware> logger, Stream originalResponseBody)
        {
            response.Seek(0, SeekOrigin.Begin);

            logger.LogInformation($"Request.Uri: {context.Request.GetUri()}");
            logger.LogInformation(
                $"Request.Headers:{Environment.NewLine}{GetHeaders(context.Request.Headers)}");

            logger.LogInformation($"Request.Body: {originalRequestBody}");

            logger.LogInformation(
                $"Response.Headers:{Environment.NewLine}{GetHeaders(context.Response.Headers)}");
            logger.LogInformation($"Response.Body: ");
            await LogResponseBody(_logFile, response, originalResponseBody, context);
        }
コード例 #3
0
 public async Task InvokeAsync(HttpContext context, ILogger <HttpLoggingMiddleware> logger, IOptionsMonitor <ThrottlingOptions> options)
 {
     if (!options.CurrentValue.LogRequestResponse)
     {
         await _next(context);
     }
     else
     {
         using (var request = new LinkedBuffer())
             using (var response = new LinkedBuffer())
             {
                 (Stream originalResponseBody, string originalRequestBody) = Preprocess(context, response, request);
                 await _next(context);
                 await Postprocess(context, response, originalRequestBody, logger, originalResponseBody);
             }
     }
 }
コード例 #4
0
        private static async Task LogResponseBody(string _logFile, LinkedBuffer response, Stream originalResponseBody, HttpContext context)
        {
            using (var sw = new StreamWriter(_logFile, true))
                using (var sr = new StreamReader(response))
                {
                    while (sr.Peek() >= 0)
                    {
                        var buffer = new char[Math.Min(response.Length, 1048576)];
                        sr.Read(buffer, 0, buffer.Length);
                        sw.Write(buffer);
                    }
                    sw.WriteLine();
                    response.Seek(0, SeekOrigin.Begin);
                    await response.CopyToAsync(originalResponseBody);

                    context.Response.Body = originalResponseBody;
                }
        }