Ejemplo n.º 1
0
        public async Task Invoke(HttpContext context, ILoggerBuilder loggingBuilder)
        {
            try
            {
                var request = await FormatRequest(context.Request);

                loggingBuilder.AddRequest(request);
                loggingBuilder.SetProperty(nameof(LoggingModel.RequestUrl),
                                           $"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}{context.Request.QueryString}");
                loggingBuilder.SetProperty(nameof(LoggingModel.RequestMethod), context.Request.Method);
                loggingBuilder.SetProperty(nameof(LoggingModel.RequestHeaders), JsonConvert.SerializeObject(context.Request.Headers));

                var originalBodyStream = context.Response.Body;

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

                    await _next(context);

                    var response = await FormatResponse(context.Response);

                    await responseBody.CopyToAsync(originalBodyStream);

                    loggingBuilder.AddResponse(response);
                    loggingBuilder.SetProperty(nameof(LoggingModel.HttpStatus), context.Response.StatusCode);
                    loggingBuilder.SetProperty(nameof(LoggingModel.HostIp), GetHostIp());
                    loggingBuilder.SetProperty(nameof(LoggingModel.ClientIp), context.Features.Get <IHttpConnectionFeature>()?.RemoteIpAddress?.ToString());
                    var loggingModel = loggingBuilder.GetLogging();

                    //TODO:Save API request and response in DB or File
                }
            }
            catch (Exception ex)
            {
                //TODO: file log in case of logging failure or invalidate the request based on your business
            }
        }