Ejemplo n.º 1
0
        private async Task <ApiLogEntry> FormatRequest(HttpContext context, bool logBody)
        {
            HttpRequest request = context.Request;

            string      requestUri  = $"{request.Scheme}://{request.Host}{request.Path}{request.QueryString}";
            ApiLogEntry returnValue = new ApiLogEntry
            {
                RequestId   = (string)context.Items[Constants.CONTEXT_CORRELATION_ID],
                Application = "core-service",
                User        = context.User.Identity.Name,
                //User = "******",
                RequestContentType = request.ContentType,
                RequestIpAddress   = context.Connection.RemoteIpAddress.ToString(),
                RequestMethod      = request.Method,
                RequestHeaders     = LoggerService.SerializeHeaders(request.Headers),
                RequestTimestamp   = DateTime.Now,
                RequestUri         = requestUri
            };

            if (logBody)
            {
                var body = request.Body;

                //This line allows us to set the reader for the request back at the beginning of its stream.
                request.EnableRewind();

                returnValue.RequestContentBody = await new StreamReader(request.Body).ReadToEndAsync();

                request.Body.Position = 0;
            }
            return(returnValue);
        }
Ejemplo n.º 2
0
        public async Task Invoke(HttpContext context)
        {
            bool logRequestBody  = !apiRequestBlackList.Contains(context.Request.Path);
            bool logResponseBody = !apiResponseBlackList.Contains(context.Request.Path);

            //First, get the incoming request
            ApiLogEntry apiLogEntry = await FormatRequest(context, logRequestBody);

            //Copy a pointer to the original response body stream
            Stream originalBodyStream = context.Response.Body;

            //Create a new memory stream...
            using (MemoryStream responseBody = new MemoryStream())
            {
                //...and use that for the temporary response body
                context.Response.Body = responseBody;

                //Continue down the Middleware pipeline, eventually returning to this class
                await _next(context);

                //Format the response from the server
                apiLogEntry = await FormatResponse(context, apiLogEntry, logResponseBody);

                //Copy the contents of the new memory stream (which contains the response) to the original stream, which is then returned to the client.
                await responseBody.CopyToAsync(originalBodyStream);
            }

            LoggerService.SaveApiLogEntry(apiLogEntry);
        }
Ejemplo n.º 3
0
    private async Task Log(DateTime start, HttpRequestMessage request,
                           HttpResponseMessage response, string requestContent,
                           string responseContent)
    {
        var finished = DateTime.UtcNow;
        var info     = new ApiLogEntry(start, finished, requestContent, responseContent,
                                       request, response);

        Data.Log(info);
    }
Ejemplo n.º 4
0
        /// <summary>
        /// Saves api call to file at Log folder.
        /// </summary>
        /// <param name="entry"><see cref="ApiLogEntry"/> entry.</param>
        private void saveEntry(ApiLogEntry entry)
        {
            var day  = entry.RequestTimestamp.ToString("dd-MM-yyyy", CultureInfo.InvariantCulture);
            var path = AppDomain.CurrentDomain.GetData("DataDirectory").ToString() + "/Log/" + day + ".txt";

            if (File.Exists(path))
            {
                File.AppendAllText(path, ",");
            }

            File.AppendAllText(path, JsonConvert.SerializeObject(entry, Formatting.Indented));
        }
Ejemplo n.º 5
0
        public void Log(ApiLogEntry logEntry)
        {
            var result = new ApiLog()
            {
                AbsoluteUri         = logEntry.AbsoluteUri,
                Host                = logEntry.Host,
                RequestBody         = logEntry.RequestContentBody,
                RequestIpAddress    = logEntry.RequestIpAddress,
                RequestMethod       = logEntry.RequestMethod,
                RequestTimestamp    = logEntry.RequestTimestamp.Value,
                RequestUri          = logEntry.RequestUri,
                ResponseContentBody = logEntry.ResponseContentBody,
                ResponseStatusCode  = logEntry.ResponseStatusCode,
                ResponseTimestamp   = logEntry.ResponseTimestamp
            };

            _db.ApiLogs.Add(result);
            _db.SaveChanges();
        }
Ejemplo n.º 6
0
        internal static async Task <IRestResponse <T> > SendAsync <T>(TeamHttpContext teamHttpContext, string url, Method method, dynamic data = null) where T : new()
        {
            RestClient  restClient  = new RestClient(url);
            RestRequest restRequest = new RestRequest(string.Empty, method);

            restRequest.AddHeader(Constants.HEADER_CONTENT_TYPE, "application/json");
            ApiLogEntry logEntry = LoggerService.SaveApiLogEntry(teamHttpContext, url, restRequest);

            if (data != null)
            {
                restRequest.AddJsonBody(data);
            }

            IRestResponse <T> restResponse = await restClient.ExecuteTaskAsync <T>(restRequest).ConfigureAwait(false);

            LoggerService.UpdateApiLogEntry(logEntry, restResponse);

            return(restResponse);
        }
        private async Task <ApiLogEntry> HydrateApiLogEntryAsync(HttpRequestMessage request)
        {
            var context     = ((HttpContextBase)request.Properties["MS_HttpContext"]);
            var routeData   = request.GetRouteData();
            var apiLogEntry = new ApiLogEntry
            {
                CorrelationId          = request.GetCorrelationId().ToString(),
                Application            = "mockingbird",
                User                   = context.User.Identity.Name,
                Machine                = Environment.MachineName,
                RequestContentType     = context.Request.ContentType,
                RequestRouteTemplate   = routeData.Route.RouteTemplate,
                RequestRouteData       = SerializeRouteData(routeData),
                RequestIpAddress       = context.Request.UserHostAddress,
                RequestMethod          = request.Method.Method,
                RequestHeaders         = SerializeHeaders(request.Headers),
                RequestTimestamp       = DateTime.Now,
                RequestUriPathAndQuery = request.RequestUri.PathAndQuery
            };

            return(await Task.FromResult(apiLogEntry));
        }
Ejemplo n.º 8
0
        public void Write(ApiLogEntry data)
        {
            string json = JsonConvert.SerializeObject(data, Formatting.Indented);
            var    now  = DateTime.Now;

            var folderpath = ConfigurationManager.AppSettings["RequestResponseLog"];

            if (!System.IO.Directory.Exists(folderpath))
            {
                System.IO.Directory.CreateDirectory(folderpath);
            }
            var path = "RequestResponse_" + now.Hour + now.Minute + now.Second + now.Millisecond + ".log";

            try
            {
                System.IO.File.AppendAllText(Path.Combine(folderpath, path), json);
            }
            catch (Exception ex)
            {
                // eat
            }
        }
Ejemplo n.º 9
0
        private async Task <ApiLogEntry> FormatResponse(HttpContext httpContext, ApiLogEntry apiLogEntry, bool logBody)
        {
            HttpResponse response = httpContext.Response;

            if (logBody)
            {
                //We need to read the response stream from the beginning...
                response.Body.Seek(0, SeekOrigin.Begin);

                //...and copy it into a string
                apiLogEntry.ResponseContentBody = await new StreamReader(response.Body).ReadToEndAsync();
            }
            //We need to reset the reader for the response so that the client can read it.
            response.Body.Seek(0, SeekOrigin.Begin);

            apiLogEntry.ResponseStatusCode = response.StatusCode;
            apiLogEntry.ResponseHeaders    = LoggerService.SerializeHeaders(response.Headers);
            apiLogEntry.User = httpContext.User.Identity.Name;

            //Return the string for the response, including the status code (e.g. 200, 404, 401, etc.)
            return(apiLogEntry);
        }
Ejemplo n.º 10
0
 public ApiEntryCommand(ApiLogEntry entry, List <TraceStep> steps)
 {
     Entry = entry;
     Steps = steps;
 }
Ejemplo n.º 11
0
        public async Task Invoke(HttpContext context)
        {
            var responseLoggerStream = new ResponseLoggerStream(context.Response.Body, ownsParent: false);

            context.Response.Body = responseLoggerStream;

            var requestLoggerStream = new RequestLoggerStream(context.Request.Body, ownsParent: false);

            context.Request.Body = requestLoggerStream;

            try
            {
                var watch = Stopwatch.StartNew();
                await _next.Invoke(context);

                watch.Stop();
                var requestUri = $"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}";

                if (context.Request.QueryString.HasValue)
                {
                    requestUri += $"?{context.Request.QueryString}";
                }

                var headerBuilder = new StringBuilder();
                headerBuilder.AppendLine("Headers:");
                headerBuilder.AppendLine("{");

                foreach (var header in context.Request.Headers)
                {
                    headerBuilder.AppendLine($"{header.Key}:{header.Value}");
                }

                headerBuilder.AppendLine("}");

                var requestTracerStream = requestLoggerStream.TracerStream;
                var requestData         = requestTracerStream.ToArray();
                var requestContent      = Encoding.UTF8.GetString(requestData);

                var responseTracerStream = responseLoggerStream.TracerStream;

                var responseData    = responseTracerStream.ToArray();
                var responseContent = Encoding.UTF8.GetString(responseData);

                string apiKey        = context.Request.Headers["apikey"];
                string userAgent     = context.Request.Headers["User-Agent"];
                string transactionId = context.Request.Headers["transactionID"];

                var entry = new ApiLogEntry
                {
                    HostName                = Environment.MachineName,
                    ApplicationName         = _hostingEnvironment.ApplicationName,
                    RequestURI              = requestUri,
                    RequestContentType      = context.Request.ContentType ?? string.Empty,
                    RequestMethod           = context.Request.Method,
                    RequestIPAddress        = context.Connection.RemoteIpAddress.ToString(),
                    RequestContent          = headerBuilder + "\r\n" + requestContent,
                    RequestCreated          = DateTime.Now,
                    RequestAPIKey           = string.IsNullOrEmpty(apiKey) ? "N/A" : apiKey,
                    RequestUserAgent        = string.IsNullOrEmpty(userAgent) ? "N/A" : userAgent,
                    RequestTransactionID    = string.IsNullOrEmpty(transactionId) ? "N/A" : transactionId,
                    RequestUserID           = context.Request.Headers["sfUserID"].ToString() ?? context.Request.Headers["userID"].ToString(),
                    RequestUserName         = context.Request.Headers["sfUserName"],
                    RequestUserLocation     = null,
                    RequestTimeStamp        = context.Request.Headers["requestedTimeStamp"],
                    ResponseCode            = context.Response.StatusCode.ToString(),
                    ResponseCodeDescription = context.Response.StatusCode.ToString(),
                    ResponseContent         = responseContent,
                    ResponseContentType     = string.IsNullOrEmpty(context.Response.ContentType) ? "NA" : context.Response.ContentType,
                    ResponseCreated         = DateTime.Now,
                };

                using (var connection = _apiLoggingConnectionProvider.CreateSqlConnection())
                {
                    try
                    {
                        connection.Execute("dbo.OneGovAPIRequestResponseInsert", entry, commandType: CommandType.StoredProcedure);
                    }
                    catch (Exception ex)
                    {
                        var e = ex;
                    }
                }
            }
            finally
            {
                context.Response.Body = responseLoggerStream.Inner;
                responseLoggerStream.Dispose();

                context.Request.Body = requestLoggerStream.Inner;
                requestLoggerStream.Dispose();
            }
        }