public async Task Invoke(HttpContext context, IApiLogService apiLogService)
        {
            apiLogService.Log.LogStartTime = DateTime.Now.Millisecond.ToString();



            var request = await FormatRequest(context.Request);

            apiLogService.Log.Request = request;



            var originalBodyStream = context.Response.Body;


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

                await _next(context);

                var response = await FormatResponse(context.Response);

                apiLogService.Log.Response = response;


                await responseBody.CopyToAsync(originalBodyStream);
            }

            apiLogService.Log.LogEndTime = DateTime.Now.Millisecond.ToString();

            apiLogService.Create(apiLogService.Log);
        }
예제 #2
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var            authHeaderValue = request.Headers.GetValues(ApiConstants.AuthorizationHeaderName).FirstOrDefault();
            Maybe <ApiKey> maybeKey        = Maybe <ApiKey> .Nothing;

            if (!string.IsNullOrEmpty(authHeaderValue))
            {
                maybeKey = _keyRepository.Get(authHeaderValue);
            }

            var apiLog = _logService.Create();

            apiLog.Ip               = request.GetClientIpAddress();
            apiLog.Key              = authHeaderValue;
            apiLog.KeyId            = maybeKey.HasValue ? maybeKey.Value.Id : (int?)null;
            apiLog.RequestTimestamp = DateTime.Now;
            apiLog.RequestContent   = request.Content.ReadAsStringAsync().Result;
            apiLog.RequestMethod    = request.Method.Method;
            apiLog.RequestUrl       = request.RequestUri.ToString();

            HttpResponseMessage response = null;

            try
            {
                response = await base.SendAsync(request, cancellationToken);

                apiLog.ResponseTimestamp  = DateTime.Now;
                apiLog.ResponseContent    = response.Content.ReadAsStringAsync().Result;
                apiLog.ResponseStatusCode = response.StatusCode;
            }
            catch
            {
            }
            finally
            {
                _logService.Save(apiLog);
            }

            return(response);
        }
예제 #3
0
        //<summary>Recibe la peticion del servidor antes de que llegue al controlador para realzar el log de la peticion.</summary>
        /// <param name="cancellationToken"></param>
        /// <param name="request">Objeto que contiene informacion de las peticiones.</param>
        /// <returns>Respuesta del servidor</returns>
        protected override async System.Threading.Tasks.Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            using (IUnitOfWork unitOfWork = new UnitOfWork())
            {
                IRepository <ApiLog> repository     = new Repository <ApiLog>(unitOfWork);
                IRepository <User>   repositoryUser = new Repository <User>(unitOfWork);
                apiLogService = new ApiLogService(repository);
                userService   = new UserService(repositoryUser);

                StringBuilder                 content                = new StringBuilder();
                string                        requestUuid            = request.GetCorrelationId().ToString();
                HttpConfiguration             config                 = GlobalConfiguration.Configuration;
                IHttpRouteData                routeData              = config.Routes.GetRouteData(request);
                HttpControllerContext         controllerContext      = new HttpControllerContext(config, routeData, request);
                DefaultHttpControllerSelector controllerSelector     = new DefaultHttpControllerSelector(config);
                HttpControllerDescriptor      controllerDescriptor   = controllerSelector.SelectController(request);
                ApiControllerActionSelector   apiControllerSelection = new ApiControllerActionSelector();
                controllerContext.ControllerDescriptor = controllerDescriptor;
                HttpActionDescriptor actionDescriptor = apiControllerSelection.SelectAction(controllerContext);
                ApiLog requestLog = new ApiLog();
                requestLog.Uuid       = requestUuid;
                requestLog.Controller = controllerDescriptor.ControllerName;
                requestLog.Action     = actionDescriptor.ActionName;
                //Obtiene y decodifica el post para que se muestre la informacion de la manera adecuada
                string data = HttpUtility.UrlDecode(request.Content.ReadAsStringAsync().Result);
                requestLog.Data      = data;
                requestLog.CreatedAt = DateTime.Now;
                requestLog.Url       = request.RequestUri.AbsoluteUri;//request.RequestUri.Host + HttpUtility.UrlDecode(request.RequestUri.PathAndQuery);
                requestLog.Method    = request.Method.Method;
                requestLog.Status    = "Started";
                object headers = request.Headers.ToDictionary(x => x.Key, y => y.Value);
                requestLog.Headers = JsonConvert.SerializeObject(headers);
                //unitOfWork.BeginTransaction();
                try
                {
                    apiLogService.Create(requestLog);
                    //unitOfWork.Commit();
                }
                catch (Exception e)
                {
                    //unitOfWork.Rollback();
                }
                //Se espera la respuesta del controlador
                var response = await base.SendAsync(request, cancellationToken);

                requestUuid = request.GetCorrelationId().ToString();
                //unitOfWork.BeginTransaction();
                try
                {
                    requestLog = apiLogService.FindBy(x => x.Uuid == requestUuid).FirstOrDefault();
                    User user   = null;
                    int? userId = UserApiAuthenticated.GetUserAuthenticatedId(request.GetRequestContext());
                    if (userId.HasValue)
                    {
                        user = userService.GetById(userId.Value);
                    }
                    if (user != null)
                    {
                        requestLog.CreatedBy = user;
                    }
                    if (requestLog != null)
                    {
                        if (response.RequestMessage != null && response.Content != null)
                        {
                            var responseContent = await response.Content.ReadAsStringAsync();

                            if (requestLog.Exception != null)
                            {
                                requestLog.Status = "HasException";
                            }
                            else
                            {
                                requestLog.Status = "Completed";
                            }
                            requestLog.Result = responseContent.ToString();
                            apiLogService.Update(requestLog);
                        }
                    }
                    //unitOfWork.Commit();
                }catch (Exception e)
                {
                    //unitOfWork.Rollback();
                }
                return(response);
            }
        }