예제 #1
0
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            BaseResponse errorResponse = new BaseResponse();

            if (actionContext.ActionArguments.Any(a => a.Value == null))
            {
                errorResponse.AddErrorMessage("Provided request body cannot be serialized.");
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, errorResponse);
                return;
            }

            if (!actionContext.ModelState.IsValid)
            {
                foreach (ModelState modelState in actionContext.ModelState.Values)
                {
                    if (modelState.Errors.HasElements())
                    {
                        foreach (ModelError modelStateError in modelState.Errors)
                        {
                            errorResponse.AddErrorMessage(modelStateError.ErrorMessage);
                        }
                    }
                }

                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, errorResponse);
                return;
            }

            base.OnActionExecuting(actionContext);
        }
        public override void OnActionExecuting(ActionExecutingContext actionContext)
        {
            BaseResponse errorResponse = new BaseResponse();

            if (!actionContext.ModelState.IsValid)
            {
                foreach (var modelState in actionContext.ModelState.Values)
                {
                    if (modelState.Errors.HasElements())
                    {
                        foreach (ModelError modelStateError in modelState.Errors)
                        {
                            errorResponse.AddErrorMessage(modelStateError.GetErrorMessage());
                        }
                    }
                }
            }

            if (errorResponse.HasError)
            {
                var errorResult = new ObjectResult(errorResponse)
                {
                    StatusCode = 400
                };

                Logger?.LogTrace($"{actionContext.ActionDescriptor.DisplayName} is called with wrong arguments. {errorResponse.ToJson()}");

                actionContext.Result = errorResult;
            }

            base.OnActionExecuting(actionContext);
        }
예제 #3
0
        public override void OnEntry(MethodExecutionArgs args)
        {
            if (args.Arguments == null || args.Arguments.Count == 0)
            {
                throw new InvalidOperationException("A method without and parameters cannot be validated.");
            }

            MethodInfo methodInfo = args.Method as MethodInfo;

            if (methodInfo == null)
            {
                throw new InvalidOperationException("Cannot get method info from PostSharp.");
            }

            if (!methodInfo.ReturnType.IsSubclassOf(typeof(BaseResponse)))
            {
                throw new InvalidOperationException("Only methods that return a type that's inherited from BaseResponse can be validates with this attribute.");
            }

            foreach (object argument in args.Arguments)
            {
                if (argument == null)
                {
                    BaseResponse response = Activator.CreateInstance(methodInfo.ReturnType) as BaseResponse;
                    response.AddErrorMessage("Invalid request.");
                    args.FlowBehavior = FlowBehavior.Return;
                    args.ReturnValue  = response;
                    return;
                }

                Type requestType = argument.GetType();

                ValidatorAttribute validatorAttribute = requestType.GetCustomAttribute <ValidatorAttribute>();

                if (validatorAttribute != null)
                {
                    IValidator       validator        = (IValidator)Activator.CreateInstance(validatorAttribute.ValidatorType);
                    ValidationResult validationResult = validator.Validate(args.Arguments[0]);

                    if (!validationResult.IsValid)
                    {
                        BaseResponse response = Activator.CreateInstance(methodInfo.ReturnType) as BaseResponse;

                        if (response == null)
                        {
                            throw new InvalidOperationException($"Cannot initialize a BaseResponse for type {methodInfo.ReturnType.Name}.");
                        }

                        response.Messages = validationResult.GetErrors();

                        args.FlowBehavior = FlowBehavior.Return;
                        args.ReturnValue  = response;
                        return;
                    }
                }
            }
        }
        private async Task <TResult> SendApiRequest <TResult>(BaseResponse response, Task <HttpResponseMessage> httpRequestTask)
        {
            try
            {
                var getRequestResponse = await httpRequestTask;
                var apiResponse        = getRequestResponse.EnsureSuccessStatusCode();

                if (!apiResponse.IsSuccessStatusCode)
                {
                    var message = string.Format(
                        CultureInfo.InvariantCulture,
                        Resource.HeroApi_FailedResponseMessageFormat,
                        apiResponse.ReasonPhrase,
                        apiResponse.StatusCode);

                    response.AddErrorMessage(message);

                    return(default);
 public static void AddNotFoundMessage(this BaseResponse baseResponse)
 {
     baseResponse.AddErrorMessage(Constants.MessageTypes.NotFound);
 }