Ejemplo n.º 1
0
        public async Task InvokeAsync(HttpContext context)
        {
            HttpStatusCode code;

            try
            {
                await _next(context);
            }
            catch (ArgumentException ex)
            {
                var headers = string.Join(Environment.NewLine, context.Request.Headers.Select(x => $"{x.Key}:{x.Value}"));

                code = HttpStatusCode.BadRequest;

                _logger.LogWarning(ex, LogMessageComposer.Compose(
                                       new
                {
                    user      = context.User.Identity?.Name ?? "anonymous",
                    message   = ex.Message,
                    parameter = ex.ParamName,
                    method    = ex.TargetSite.ReflectedType.FullName,
                }));

                context.Response.StatusCode = (int)code;
                await context.Response.WriteAsync(new UserErrorDetails()
                {
                    StatusCode = (int)code,
                    Message    = $"{ex.Message}"
                }.ToString());
            }
            catch (Exception ex)
            {
                code = HttpStatusCode.BadRequest;


                _logger.LogCritical(ex,
                                    LogMessageComposer.Compose(
                                        new
                {
                    user       = context.User.Identity?.Name ?? "anonymous",
                    message    = ex.Message,
                    targetsite = ex.TargetSite.Name,
                    uri        = context.Request.Path,
                    method     = context.Request.Method,
                }));

                context.Response.StatusCode = (int)code;
                await context.Response.WriteAsync(new UserErrorDetails()
                {
                    StatusCode = (int)code,
                    Message    = "An error occurred. Please try again."
                }.ToString());
            }
        }
Ejemplo n.º 2
0
        public override Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            return(Task.Run(() =>
            {
                var request = actionContext.Request;

                _log.Info(LogMessageComposer.Compose(
                              new
                {
                    details = "Action executing started",
                    method = request.Method,
                    url = request.RequestUri,
                    userIP = ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress
                }));
            }));
        }
Ejemplo n.º 3
0
        private void WrapAndLogException(HttpActionExecutedContext context)
        {
            var            exception = context.Exception;
            HttpStatusCode code;
            string         message;

            if (exception is CustomApiException customException)
            {
                code    = customException.Code;
                message = JsonConvert.SerializeObject(new { Reason = customException.Message, customException.Fields });
            }
            else
            {
                if (exception is ItemNotFoundException || exception is PublisherNotFoundException)
                {
                    code = HttpStatusCode.NoContent;
                }
                else
                {
                    code = HttpStatusCode.InternalServerError;
                }

                var r = context.Request;

                _log.Error(exception,
                           LogMessageComposer.Compose(
                               new
                {
                    details = "Http request failed",
                    method  = r.Method,
                    url     = r.RequestUri,
                    userIP  = ((HttpContextWrapper)r.Properties["MS_HttpContext"]).Request.UserHostAddress,
                    message = exception.Message
                }));

                message = JsonConvert.SerializeObject(new { Reason = "An error occurred. Please try again." });
            }

            context.Response = context.Request.CreateErrorResponse(code, message);
        }
Ejemplo n.º 4
0
        private HttpResponseMessage WrapAndLogValidationError(HttpActionContext actionContext)
        {
            var invalidProperties = actionContext.ModelState.Where(m => m.Value.Errors.Any());

            var validationErrorCollection = invalidProperties.Select(x =>
            {
                var errors = x.Value.Errors.Select((e => String.IsNullOrEmpty(e.ErrorMessage)
                        ? Regex.Replace(e.Exception.Message, @"\.(.*)", String.Empty)
                        : e.ErrorMessage));

                var prefix = String.IsNullOrEmpty(x.Key) ? "Summary" : x.Key;
                return(new { key = prefix, value = errors });
            }).ToDictionary(x => x.key, x => x.value);

            _log.Warn(LogMessageComposer.Compose(
                          new
            {
                details    = "Model validation failed",
                user       = "******",
                modelState = validationErrorCollection
            }));

            throw new CustomApiException(HttpStatusCode.BadRequest, "Resource validation failed.", validationErrorCollection);
        }