Ejemplo n.º 1
0
        private async Task LogResponse(HttpResponse resp, RequestLog log, Stopwatch timer,
                                       DbCore dbc, string ExceptionMessage = null)
        {
            bool hasException = ExceptionMessage != null;

            dbc.Entry(log);
            log.ResponseStatus      = hasException ? 500 : resp.StatusCode;
            log.ResponseContentType = resp.Headers.GetValueOrDefault("Content-Type", "");
            //ContentLength not always set. Fallback to buffer length if unset
            log.ResponseSize = (int)(resp.ContentLength ?? resp.Body.Length);
            log.Location     = resp.Headers.GetValueOrDefault("Location", "");
            //TODO: log.ResponseType = ???!!!

            //Earlier, the response.body stream was replaced with one that allows rewinding
            //so rewind to beginning, read it, and rewind it again.
            resp.Body.Seek(0, SeekOrigin.Begin);
            string responseAsText = await new StreamReader(resp.Body).ReadToEndAsync();

            resp.Body.Seek(0, SeekOrigin.Begin);

            if (!responseAsText.IsNullOrWhitespace())
            {
                log.ResponseText = responseAsText.Left(ResponseLogLength);
            }
            else if (hasException)
            {
                log.ResponseText  = "Unhandled exception: ";
                log.ResponseText += ExceptionMessage.Left(ResponseLogLength - log.ResponseText.Length);
            }

            //Do as much work as possible before getting the time
            log.ResponseMs = (decimal)timer.Elapsed.TotalMilliseconds;

            await dbc.SaveChangesAsync();
        }