/// <summary>
        /// OnException
        /// </summary>
        /// <param name="context"></param>
        public override void OnException(HttpActionExecutedContext context)
        {
            var trace = GlobalConfiguration.Configuration.Services.GetTraceWriter();

            if (trace == null)
            {
                return;
            }

            APILogHelper apiLogHelper = new APILogHelper();
            var          apiLogEntry  = apiLogHelper.CreateApiLogEntryWithRequestData(context.Request);

            trace.Error(context.Request, _module, "JSON", apiLogEntry);

            //trace.Error(context.Request,
            //    "Controller : " + context.ActionContext.ControllerContext.ControllerDescriptor.ControllerType.FullName +
            //    Environment.NewLine + "Action : " + context.ActionContext.ActionDescriptor.ActionName, context.Exception);

            var exceptionType = context.Exception.GetType();

            if (exceptionType == typeof(ValidationException))
            {
                var resp = new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new StringContent(context.Exception.Message), ReasonPhrase = "ValidationException",
                };
                throw new HttpResponseException(resp);
            }
            else if (exceptionType == typeof(UnauthorizedAccessException))
            {
                throw new HttpResponseException(context.Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                                               new ErrorHandling.WebException()
                {
                    HttpStatusCode    = HttpStatusCode.Unauthorized,
                    HataAciklama      = "UnAuthorized",
                    HataDetayAciklama = "UnAuthorized Access",
                }));
            }
            else if (exceptionType == typeof(ErrorHandling.WebException))
            {
                var webApiException = context.Exception as ErrorHandling.WebException;

                if (webApiException != null)
                {
                    throw new HttpResponseException(context.Request.CreateResponse(webApiException.HttpStatusCode, webApiException));
                }
            }
            else
            {
                throw new HttpResponseException(context.Request.CreateResponse(HttpStatusCode.InternalServerError));
            }
        }
Esempio n. 2
0
        public override async Task Invoke(IOwinContext owinContext)
        {
            try
            {
                await Next.Invoke(owinContext);
            }
            catch (Exception ex)
            {
                try
                {
                    handleException(ex, owinContext);
                    var exceptionGuid = ex.Data["httpRequestMessageGuid"];
                    var module        = ex.Data["module"];

                    if (exceptionGuid != null && module != null)
                    {
                        HttpRequestMessage httpRequestMessage;
                        bool result = ServiceLocator.GetService <HttpRequestMessageService>().HttpRequestMessageDict.TryGetValue(exceptionGuid.ToString(), out httpRequestMessage);

                        var trace = GlobalConfiguration.Configuration.Services.GetTraceWriter();

                        if (trace == null)
                        {
                            return;
                        }

                        APILogHelper apiLogHelper = new APILogHelper();
                        var          apiLogEntry  = apiLogHelper.CreateApiLogEntryWithRequestData(httpRequestMessage);


                        apiLogEntry.ResponseContentBody   = string.Empty; // owinContext.Response.Body.Read
                        apiLogEntry.ResponseContentType   = owinContext.Response.ContentType;
                        apiLogEntry.ResponseHeaders       = JsonConvert.SerializeObject(owinContext.Response.Headers, Formatting.Indented);
                        apiLogEntry.ResponseStatusCode    = owinContext.Response.StatusCode;
                        apiLogEntry.ResponseTimestamp     = DateTime.UtcNow;
                        apiLogEntry.TotalExecutionSeconds = (apiLogEntry.ResponseTimestamp - apiLogEntry.RequestTimestamp).Value.TotalSeconds;

                        trace.Error(httpRequestMessage, module.ToString(), ex, "JSON", apiLogEntry);
                    }

                    return;
                }
                catch (Exception unhandledException)
                {
                    handleException(unhandledException, owinContext);
                    // If there's a Exception while generating the error page, re-throw the original exception.
                }
                throw;
            }
        }
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var apiLogEntry = _apiLogHelper.CreateApiLogEntryWithRequestData(request);

            if (apiLogEntry == null)
            {
                return(await base.SendAsync(request, cancellationToken));
            }

            if (request.Content != null)
            {
                await request.Content.ReadAsStringAsync().ContinueWith(task => {
                    apiLogEntry.RequestContentBody = task.Result;
                }, cancellationToken);
            }

            return(await base.SendAsync(request, cancellationToken).ContinueWith(task => {
                var response = task.Result;

                // Update the API log entry with response info
                apiLogEntry.ResponseStatusCode = (int)response.StatusCode;
                apiLogEntry.ResponseTimestamp = DateTime.UtcNow;
                apiLogEntry.TotalExecutionSeconds = (apiLogEntry.ResponseTimestamp.Value - apiLogEntry.RequestTimestamp.Value).TotalSeconds;

                if (response.Content != null)
                {
                    apiLogEntry.ResponseContentBody = response.Content.ReadAsStringAsync().Result;
                    apiLogEntry.ResponseContentType = response.Content.Headers.ContentType.MediaType;
                    apiLogEntry.ResponseHeaders = _apiLogHelper.SerializeHeaders(response.Content.Headers);
                }

                // TODO: Save the API log entry to the database
                var trace = GlobalConfiguration.Configuration.Services.GetTraceWriter();

                if (trace == null)
                {
                    return response;
                }

                trace.Info(request, _module, "JSON", apiLogEntry);

                return response;
            }, cancellationToken));
        }