public static async Task ResponseFilterAsync(IRequest req, IResponse res, object requestDto)
        {
            if (!(requestDto is IHasResponseStatus response))
            {
                return;
            }

            var validator = ValidatorCache.GetValidator(req, req.Dto.GetType());

            if (validator == null)
            {
                return;
            }

            var validationResult = await Validate(validator, req, req.Dto);

            var responseStatus = response.ResponseStatus
                                 ?? DtoUtils.CreateResponseStatus(validationResult.Errors[0].ErrorCode);

            foreach (var error in validationResult.Errors)
            {
                var responseError = new ResponseError
                {
                    ErrorCode = error.ErrorCode,
                    FieldName = error.PropertyName,
                    Message   = error.ErrorMessage,
                    Meta      = new Dictionary <string, string> {
                        ["Severity"] = error.Severity.ToString()
                    }
                };
                responseStatus.Errors.Add(responseError);
            }

            response.ResponseStatus = responseStatus;
        }
Beispiel #2
0
        private static async Task RequestFilterAsync(IRequest req, IResponse res, object requestDto,
                                                     bool treatInfoAndWarningsAsErrors)
        {
            var validator = ValidatorCache.GetValidator(req, requestDto.GetType());

            if (validator == null)
            {
                return;
            }

            try
            {
                var validationResult = await Validate(validator, req, requestDto);

                if (treatInfoAndWarningsAsErrors && validationResult.IsValid)
                {
                    return;
                }

                if (!treatInfoAndWarningsAsErrors &&
                    (validationResult.IsValid || validationResult.Errors.All(v => v.Severity != Severity.Error)))
                {
                    return;
                }

                var errorResponse =
                    await HostContext.RaiseServiceException(req, requestDto, validationResult.ToException())
                    ?? DtoUtils.CreateErrorResponse(requestDto, validationResult.ToErrorResult());

                var validationFeature = HostContext.GetPlugin <ValidationFeature>();
                if (validationFeature?.ErrorResponseFilter != null)
                {
                    errorResponse = validationFeature.ErrorResponseFilter(validationResult, errorResponse);
                }

                await res.WriteToResponse(req, errorResponse);
            }
            catch (Exception ex)
            {
                var validationEx = ex.UnwrapIfSingleException();

                var errorResponse = await HostContext.RaiseServiceException(req, requestDto, validationEx)
                                    ?? DtoUtils.CreateErrorResponse(requestDto, validationEx);

                await res.WriteToResponse(req, errorResponse);
            }
            finally
            {
                using (validator as IDisposable)
                {
                }
            }
        }
        public static Task RequestFilterAsync(IRequest req, IResponse res, object requestDto)
        {
            var validator = ValidatorCache.GetValidator(req, requestDto.GetType());
            var ruleSet   = req.Verb;

            if (validator == null || !validator.HasAsyncValidators(ruleSet))
            {
                return(TypeConstants.EmptyTask);
            }

            var validateTask = validator.ValidateAsync(
                new ValidationContext(requestDto, null, new MultiRuleSetValidatorSelector(ruleSet))
            {
                Request = req
            });

            return(HostContext.Async.ContinueWith(req, validateTask, t =>
            {
                if (t.IsFaulted)
                {
                    var validationEx = t.Exception.UnwrapIfSingleException();

                    var errorResponse = HostContext.RaiseServiceException(req, requestDto, validationEx)
                                        ?? DtoUtils.CreateErrorResponse(requestDto, validationEx);

                    return res.WriteToResponse(req, errorResponse);
                }
                else
                {
                    var validationResult = t.Result;
                    if (validationResult.IsValid)
                    {
                        return TypeConstants.TrueTask;
                    }

                    var errorResponse = HostContext.RaiseServiceException(req, requestDto, validationResult.ToException())
                                        ?? DtoUtils.CreateErrorResponse(requestDto, validationResult.ToErrorResult());

                    var validationFeature = HostContext.GetPlugin <ValidationFeature>();
                    if (validationFeature?.ErrorResponseFilter != null)
                    {
                        errorResponse = validationFeature.ErrorResponseFilter(validationResult, errorResponse);
                    }

                    return res.WriteToResponse(req, errorResponse);
                }
            })
                   .ContinueWith(t =>
            {
                using (validator as IDisposable) { }
            }));
        }
        public static void RequestFilter(IRequest req, IResponse res, object requestDto)
        {
            var validator = ValidatorCache.GetValidator(req, requestDto.GetType());

            if (validator == null)
            {
                return;
            }

            try
            {
                var validatorWithHttpRequest = validator as IRequiresRequest;
                if (validatorWithHttpRequest != null)
                {
                    validatorWithHttpRequest.Request = req;
                }

                var ruleSet          = req.Verb;
                var validationResult = validator.Validate(
                    new ValidationContext(requestDto, null, new MultiRuleSetValidatorSelector(ruleSet)));

                if (validationResult.IsValid)
                {
                    return;
                }

                var errorResponse = HostContext.RaiseServiceException(req, requestDto, validationResult.ToException())
                                    ?? DtoUtils.CreateErrorResponse(requestDto, validationResult.ToErrorResult());

                var validationFeature = HostContext.GetPlugin <ValidationFeature>();
                if (validationFeature != null && validationFeature.ErrorResponseFilter != null)
                {
                    errorResponse = validationFeature.ErrorResponseFilter(validationResult, errorResponse);
                }

                res.WriteToResponse(req, errorResponse);
            }
            finally
            {
                using (validator as IDisposable) {}
            }
        }
        private static async Task RequestFilterAsync(IRequest req, IResponse res, object requestDto,
                                                     bool treatInfoAndWarningsAsErrors)
        {
            var validator = ValidatorCache.GetValidator(req, requestDto.GetType());

            if (validator == null)
            {
                return;
            }

            using (validator as IDisposable)
            {
                try
                {
                    var validationResult = await validator.ValidateAsync(req, requestDto);

                    if (treatInfoAndWarningsAsErrors && validationResult.IsValid)
                    {
                        return;
                    }

                    if (!treatInfoAndWarningsAsErrors &&
                        (validationResult.IsValid || validationResult.Errors.All(v => v.Severity != Severity.Error)))
                    {
                        return;
                    }

                    var errorResponse =
                        await HostContext.RaiseServiceException(req, requestDto, validationResult.ToException())
                        ?? DtoUtils.CreateErrorResponse(requestDto, validationResult.ToErrorResult());

                    var autoBatchIndex = req.GetItem(Keywords.AutoBatchIndex)?.ToString();
                    if (autoBatchIndex != null)
                    {
                        var responseStatus = errorResponse.GetResponseStatus();
                        if (responseStatus != null)
                        {
                            if (responseStatus.Meta == null)
                            {
                                responseStatus.Meta = new Dictionary <string, string>();
                            }
                            responseStatus.Meta[Keywords.AutoBatchIndex] = autoBatchIndex;
                        }
                    }

                    var validationFeature = HostContext.GetPlugin <ValidationFeature>();
                    if (validationFeature?.ErrorResponseFilter != null)
                    {
                        errorResponse = validationFeature.ErrorResponseFilter(req, validationResult, errorResponse);
                    }

                    await res.WriteToResponse(req, errorResponse);
                }
                catch (Exception ex)
                {
                    var validationEx = ex.UnwrapIfSingleException();

                    var errorResponse = await HostContext.RaiseServiceException(req, requestDto, validationEx)
                                        ?? DtoUtils.CreateErrorResponse(requestDto, validationEx);

                    await res.WriteToResponse(req, errorResponse);
                }
            }
        }
Beispiel #6
0
        private static async Task RequestFilterAsync(IRequest req, IResponse res, object requestDto,
                                                     bool treatInfoAndWarningsAsErrors)
        {
            var requestType = requestDto.GetType();
            await Validators.AssertTypeValidatorsAsync(req, requestDto, requestType);

            var validator = ValidatorCache.GetValidator(req, requestType);

            if (validator == null)
            {
                return;
            }

            using (validator as IDisposable)
            {
                if (validator is IHasTypeValidators hasTypeValidators && hasTypeValidators.TypeValidators.Count > 0)
                {
                    foreach (var scriptValidator in hasTypeValidators.TypeValidators)
                    {
                        await scriptValidator.ThrowIfNotValidAsync(requestDto, req);
                    }
                }

                try
                {
                    if (req.Verb == HttpMethods.Patch)
                    {
                        // Ignore property rules for AutoCrud Patch operations with default values that aren't reset (which are ignored)
                        if (validator is IServiceStackValidator ssValidator && requestDto is ICrud && requestType.IsOrHasGenericInterfaceTypeOf(typeof(IPatchDb <>)))
                        {
                            var typeProperties         = TypeProperties.Get(requestType);
                            var propsWithDefaultValues = new HashSet <string>();
                            var resetFields            = GetResetFields(req.GetParam(Keywords.reset))?.ToSet(StringComparer.OrdinalIgnoreCase)
                                                         ?? TypeConstants <string> .EmptyHashSet;

                            foreach (var entry in typeProperties.PropertyMap)
                            {
                                if (entry.Value.PublicGetter == null || resetFields.Contains(entry.Key))
                                {
                                    continue;
                                }
                                var defaultValue = entry.Value.PropertyInfo.PropertyType.GetDefaultValue();
                                var propValue    = entry.Value.PublicGetter(requestDto);
                                if (propValue == null || propValue.Equals(defaultValue))
                                {
                                    propsWithDefaultValues.Add(entry.Key);
                                }
                            }
                            if (propsWithDefaultValues.Count > 0)
                            {
                                ssValidator.RemovePropertyRules(rule => propsWithDefaultValues.Contains(rule.PropertyName));
                            }
                        }
                    }

                    var validationResult = await validator.ValidateAsync(req, requestDto);

                    if (treatInfoAndWarningsAsErrors && validationResult.IsValid)
                    {
                        return;
                    }

                    if (!treatInfoAndWarningsAsErrors &&
                        (validationResult.IsValid || validationResult.Errors.All(v => v.Severity != Severity.Error)))
                    {
                        return;
                    }

                    var errorResponse =
                        await HostContext.RaiseServiceException(req, requestDto, validationResult.ToException())
                        ?? DtoUtils.CreateErrorResponse(requestDto, validationResult.ToErrorResult());

                    var autoBatchIndex = req.GetItem(Keywords.AutoBatchIndex)?.ToString();
                    if (autoBatchIndex != null)
                    {
                        var responseStatus = errorResponse.GetResponseStatus();
                        if (responseStatus != null)
                        {
                            if (responseStatus.Meta == null)
                            {
                                responseStatus.Meta = new Dictionary <string, string>();
                            }
                            responseStatus.Meta[Keywords.AutoBatchIndex] = autoBatchIndex;
                        }
                    }

                    var validationFeature = HostContext.GetPlugin <ValidationFeature>();
                    if (validationFeature?.ErrorResponseFilter != null)
                    {
                        errorResponse = validationFeature.ErrorResponseFilter(req, validationResult, errorResponse);
                    }

                    await res.WriteToResponse(req, errorResponse);
                }
                catch (Exception ex)
                {
                    var validationEx = ex.UnwrapIfSingleException();

                    var errorResponse = await HostContext.RaiseServiceException(req, requestDto, validationEx)
                                        ?? DtoUtils.CreateErrorResponse(requestDto, validationEx);

                    await res.WriteToResponse(req, errorResponse);
                }
            }
        }
Beispiel #7
0
        public static async Task RequestFilterAsync(IRequest req, IResponse res, object requestDto)
        {
            var validator = ValidatorCache.GetValidator(req, requestDto.GetType());
            var ruleSet   = req.Verb;

            if (validator == null)
            {
                return;
            }

            try
            {
                ValidationResult validationResult;

                if (validator.HasAsyncValidators(ruleSet))
                {
                    validationResult = await validator.ValidateAsync(
                        new ValidationContext(requestDto, null, new MultiRuleSetValidatorSelector(ruleSet))
                    {
                        Request = req
                    });
                }
                else
                {
                    validationResult = validator.Validate(
                        new ValidationContext(requestDto, null, new MultiRuleSetValidatorSelector(ruleSet))
                    {
                        Request = req
                    });
                }

                if (validationResult.IsValid)
                {
                    return;
                }

                var errorResponse = await HostContext.RaiseServiceException(req, requestDto, validationResult.ToException())
                                    ?? DtoUtils.CreateErrorResponse(requestDto, validationResult.ToErrorResult());

                var validationFeature = HostContext.GetPlugin <ValidationFeature>();
                if (validationFeature?.ErrorResponseFilter != null)
                {
                    errorResponse = validationFeature.ErrorResponseFilter(validationResult, errorResponse);
                }

                await res.WriteToResponse(req, errorResponse);
            }
            catch (Exception ex)
            {
                var validationEx = ex.UnwrapIfSingleException();

                var errorResponse = await HostContext.RaiseServiceException(req, requestDto, validationEx)
                                    ?? DtoUtils.CreateErrorResponse(requestDto, validationEx);

                await res.WriteToResponse(req, errorResponse);
            }
            finally
            {
                using (validator as IDisposable) { }
            }
        }