Beispiel #1
0
        public async Task Invoke(HttpContext context)
        {
            var guid      = Guid.NewGuid();
            var stopwatch = Stopwatch.StartNew();
            var request   = await FormatRequest(context.Request);

            LogInformation($"{guid} Request: {request}");

            var originalBodyStream = context.Response.Body;

            using (var responseBody = new MemoryStream())
            {
                context.Response.Body = responseBody;

                try
                {
                    await _next(context);

                    stopwatch.Stop();
                }
                catch (Exception e)
                {
                    _logger.LogError(this.GetType().Name, e);
                }

                var response = await FormatResponse(context.Response);

                if (context.Response.ContentType != null)
                {
                    if (context.Response.ContentType.Contains("application/json"))
                    {
                        LogInformation($"{guid} ResponseTime: {stopwatch.ElapsedMilliseconds} Response: {response}");
                    }
                    else
                    {
                        LogInformation($"{guid} ResponseTime: {stopwatch.ElapsedMilliseconds} Response: {context.Response.StatusCode}");
                    }
                }

                await responseBody.CopyToAsync(originalBodyStream);
            }
        }