FluentValidation ASP.NET 核心。无法验证 IFormFile

FluentValidation ASP.NET Core. Can't to validate IFormFile

我有模型

[AutoMap(typeof(WorkDTO), ReverseMap = true)]
public class WorkDTO
{
  public Guid Id { get; set; }
  public string UserId { get; set; }
  public string Name { get; set; }
  public string AvaUrl { get; set; }
  public List<IFormFile> AvaWork { get; set; }
}

我有为此模型配置的 FluentValidator。

public WorkDtoValidator()
{
    RuleFor(p => p.Name)
        .NotNull()
        .NotEmpty()
        .Length(2, 50)
        .WithMessage("{PropertyName} should be not empty.");
    RuleFor(p => p.Description)
        .NotNull()
        .NotEmpty()
        .Length(50, 1000)
        .WithMessage("{PropertyName} should be not empty.");
    RuleFor(x => x.AvaWork).NotEmpty();
}

并在 StartUp 中配置它

services.AddControllers()
            .AddFluentValidation();
services.AddSingleton<IValidator<WorkDTO>, WorkDtoValidator>();

验证工作正常,但如果我不发送 属性 AvaWork。如果在模型中出现 AvaWork 比我得到一个异常

我试过 RuleFor(x => x.AvaWork).NotEmpty(); 同样的结果。我有一个特殊的验证class用于验证AvaWork。

public class FileValidator : AbstractValidator<IFormFile>
{
    public FileValidator()
    {
        RuleFor(x => x.Length).NotNull().LessThanOrEqualTo(100)
            .WithMessage("File size is larger than allowed");

        RuleFor(x => x.ContentType).NotNull().Must(x => x.Equals("image/jpeg") || 
        x.Equals("image/jpg") || x.Equals("image/png"))
            .WithMessage("File type is larger than allowed");
    }
}

并添加了这一行 RuleForEach(x => x.AvaWork ).SetValidator(new FileValidator()); 同样的结果。

如果在控制器中将只有 List<IFormFile> AvaWork(不是模型 public async Task<IActionResult> CreateWork(WorkDTO model)) 效果不错

我没有任何想法。

双方都有问题。在前面(Angular 11 - Typescript)我需要将所有属性添加到 formData。这样

const formData = new FormData();
formData.append('Name', this.createWorkForm.get('Name').value);
formData.append('Description', this.createWorkForm.get('description').value);


this.WorkMarkets.forEach(market => {
  formData.append('Markets', market);
});

this.WorkingHours.forEach(session => {
  formData.append('WorkingHours', session);
});

if (this.fileToUploadMain != null) {
  formData.append('AvaWork', this.fileToUploadMain, this.fileToUploadMain.name);
}

this.apiWorkService.createWork(formData).subscribe(
  suc => {
    console.log(suc);
  },
  err => {
    console.log(err);
  });

并在背面的控制器参数中添加 [FromForm]

public async Task<IActionResult> CreateWork([FromForm]WorkDTO formWork)

WorkDTO 模型

public class WorkDTO
{
    public Guid Id { get; set; }
    public string UserId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public IEnumerable<string> WorkingHours { get; set; }
    public IEnumerable<string> Markets { get; set; }
    public string AvaUrl { get; set; }
    public IFormFile AvaWork { get; set; }
}