【问题标题】:MicroElements.Swashbuckle.FluentValidation AddFluentValidationRules using the Command Handler patternMicroElements.Swashbuckle.FluentValidation AddFluentValidationRules 使用命令处理程序模式
【发布时间】:2020-01-08 12:14:02
【问题描述】:

尝试使用来自https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/microservice-application-layer-implementation-web-api 的命令处理程序模式让 MicroElements.Swashbuckle.FluentValidation 工作

使用 ASP .Net Core 2.2 MicroElements.Swashbuckle.FluentValidation v3.0.0-alpha.1(作为程序集而不是包参考) Swashbuckle.AspNetCore 5.0.0-rc2

我有这是 Startup.cs

return services.AddSwaggerGen(setup =>
            {
                setup.AddFluentValidationRules();                
            });

使用流畅的验证

这不会将 Fluent 验证提取到请求正文对象的架构中。

    public class AddModelsCommandValidator : AbstractValidator<AddModelsCommand>
    {
        public AddModelsCommandValidator()
        {
            //1. validate request
            RuleFor(e => e.Model).InvalidRequestValidation();

            When(x => x.Model != null, () =>
            {
                //2. validate request body
                RuleFor(e => e.Model.ModelCode).StringRequiredValidation();
                RuleFor(e => e.Model.ModelCode).StringMaxLengthValidation(5);
                RuleFor(e => e.Model.ProgramName).StringRequiredValidation();
                RuleFor(e => e.Model.ProgramName).StringMaxLengthValidation(50);
            });
        }
    }

    public class AddModelsCommand : IRequest<AddModelsCommandResult>
    {
        public Model Model { get; }

        public AddModelsCommand(Model model)
        {
            Model = model;
        }
    }

    public class Model
    {   
        /// <summary>
        /// Unique code of the Model
        /// </summary>
        public string ModelCode { get; set; }

        /// <summary>
        /// The name of the Program
        /// </summary>
        public string ProgramName { get; set; }
    }   

以下代码确实将 Fluent 验证提取到请求正文对象的架构中。 (因为 1. AbstractValidator 在 Model 而不是 Command 上,2. 我已经删除了条件 When() 验证)

public class AddModelsCommandValidator : AbstractValidator<Model>
    {
        public AddModelsCommandValidator()
        {

                //2. validate request body
                RuleFor(e => e.ModelCode).StringRequiredValidation();
                RuleFor(e => e.ModelCode).StringMaxLengthValidation(5);
                RuleFor(e => e.ProgramName).StringRequiredValidation();
                RuleFor(e => e.ProgramName).StringMaxLengthValidation(50);
        }
    }

有没有办法调用 AddFluentValidationRules 并使用命令处理程序模式?

【问题讨论】:

    标签: swagger asp.net-core-2.1 fluentvalidation swashbuckle


    【解决方案1】:

    这里的问题是AbstractValidator&lt;Model&gt; 必须使用.. AbstractValidator&lt;Command> 说不通

    【讨论】:

      猜你喜欢
      • 2014-06-02
      • 2021-11-24
      • 2011-08-11
      • 2016-02-16
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      • 2021-08-01
      • 2012-03-08
      相关资源
      最近更新 更多