Fluent Validation with Swagger in Asp.net Core

后端 未结 2 595
悲哀的现实
悲哀的现实 2020-12-28 19:07

I am currently using Fluent Validation instead of Data Annotations for my Web api and using swagger for API documentation. Fluent validation rules

2条回答
  •  暖寄归人
    2020-12-28 19:53

    After searching i have finally figured out that i needed to IValidationFactory for validator instance.

    public class AddFluentValidationRules : ISchemaFilter
    {
        private readonly IValidatorFactory _factory;
    
        /// 
        ///     Default constructor with DI
        /// 
        /// 
        public AddFluentValidationRules(IValidatorFactory factory)
        {
            _factory = factory;
        }
    
        /// 
        /// 
        /// 
        /// 
        public void Apply(Schema model, SchemaFilterContext context)
        {
    
            // use IoC or FluentValidatorFactory to get AbstractValidator instance
            var validator = _factory.GetValidator(context.SystemType);
            if (validator == null) return;
            if (model.Required == null)
                model.Required = new List();
    
            var validatorDescriptor = validator.CreateDescriptor();
            foreach (var key in model.Properties.Keys)
            {
                foreach (var propertyValidator in validatorDescriptor
                    .GetValidatorsForMember(ToPascalCase(key)))
                {
                    if (propertyValidator is NotNullValidator 
                      || propertyValidator is NotEmptyValidator)
                        model.Required.Add(key);
    
                    if (propertyValidator is LengthValidator lengthValidator)
                    {
                        if (lengthValidator.Max > 0)
                            model.Properties[key].MaxLength = lengthValidator.Max;
    
                        model.Properties[key].MinLength = lengthValidator.Min;
                    }
    
                    if (propertyValidator is RegularExpressionValidator expressionValidator)
                        model.Properties[key].Pattern = expressionValidator.Expression;
    
                    // Add more validation properties here;
                }
            }
        }
    
        /// 
        ///     To convert case as swagger may be using lower camel case
        /// 
        /// 
        /// 
        private static string ToPascalCase(string inputString)
        {
            // If there are 0 or 1 characters, just return the string.
            if (inputString == null) return null;
            if (inputString.Length < 2) return inputString.ToUpper();
            return inputString.Substring(0, 1).ToUpper() + inputString.Substring(1);
        }
    }
    

    and add this class to swaggerGen options

    options.SchemaFilter();
    

提交回复
热议问题