Swagger无法识别嵌套对象的Fluent Validation

本文关键字:Fluent Validation 对象 嵌套 识别 Swagger | 更新日期: 2023-09-27 18:00:16

我正在为我的模型使用Fluent Validation,并尝试使用Swagger映射字段和验证。

我有以下型号:

public abstract class PersonModel
{
    protected PersonModel()
    {
        DetailModel = new DetailModel();
    }
    public DetailModel Details { get; set; }
}
public class CustomerModel : PersonModel
{
    public DateTime DateJoined { get; set; }
}
public class DetailModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

我有以下Fluent验证的验证集:

public class CustomerModelValidator : AbstractValidator<CustomerModel>
{
    public CustomerModelValidator()
    {
        RuleFor(x => x.DetailModel.FirstName)
            .NotEmpty().WithMessage("FirstName is required");
        RuleFor(x => x.DateJoined)
            .NotEmpty().WithMessage("DateJoined is required");
    }
}

为了让Swagger理解Fluent Validation,我使用了这个网站作为参考:http://blog.yeticode.co.uk/2015/10/add-fluentvalidation-rules-to-swagger.html

为了让Swagger理解新的验证,下面的行起到了神奇的作用:

schema.required.Add("DateJoined");

但是,Swagger不理解FirstName之类的子验证。在这种情况下,如果我在字段[Required]的顶部使用数据注释,Swagger会正确地识别它。

这个博客提供的解决方案的问题是变量Schema不包含指向DetailModel字段的导航。它只包含DetailModel的定义。

但是由于FirstName没有在模式中列出,所以我无法将其添加到必需的字段中。

有人做到了吗?

Swagger无法识别嵌套对象的Fluent Validation

1.为每个类创建验证器:

public class CustomerModelValidator : AbstractValidator<CustomerModel>
{
    public CustomerModelValidator()
    {
        RuleFor(x => x.DateJoined)
            .NotEmpty().WithMessage("DateJoined is required");
    }
}
public class DetailModelValidator : AbstractValidator<DetailModel>
{
    public DetailModelValidator()
    {
        RuleFor(x => x.FirstName)
            .NotEmpty().WithMessage("FirstName is required");
    }
}
  1. 用于将fluentValidation与swagger使用包集成https://www.nuget.org/packages/MicroElements.Swashbuckle.FluentValidation/

  2. 结果:屏幕截图

由于Swagger不理解"嵌套"模型——使您的模型扁平化:

public class CustomerModel : PersonModel
{
    public DateTime DateJoined { get; set; }
}
public abstract class PersonModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

p.S.

如果这段代码是使FluentValidation在Swagger中工作的唯一原因,我强烈建议您改用DataAnnotations,因为它有更多的验证实现功能。