模型 C# 的自定义验证属性

Custom Validation Attribute for model C#

我有模型

public class SendEmail
{
    public bool IsScheduled { get; set; }
    public DateTime ScheduleDate { get; set; }
    public List<ScheduleAttachement> ScheduleAttachement {get; set;}
}
public class ScheduleAttachement
{
    public string Name { get; set; }
    public string Attachement { get; set; }
}

我想进行自定义验证以检查 bool IsScheduled == true,ScheduleAttachement 必须包含一个值。如果不抛出 400 错误请求

if (SendEmail.IsScheduled) 
{
  //true, in here you can check for a value:
  if(SendEmail.ScheduleAttachement == null || (!SendEmail.ScheduleAttachement.Any()))
  {
     //list is null or empty, throw error
  }
}

less code list null or empty 检查:

if (list?.Any() != true)
{
    //list is null or empty, throw error
}

在你的控制器

var emailToCheck = new SendEmail();

if (!emailToCheck.IsScheduled && emailToCheck.ScheduleAttachement.Count() == 0) 
{
    return BadRequest();
}

如果你想添加一个自定义消息查找这个

编辑

if (!emailToCheck.IsScheduled && emailToCheck.ScheduleAttachement?.Where(x => x.Attachment != null && x.Name != null).Count() > 0) 
{
    return BadRequest();
}