简体   繁体   English

model C# 的自定义验证属性

[英]Custom Validation Attribute for model C#

I have a model我有一个 model

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; }
}

I want to do a custom validation to check if bool IsScheduled == true, ScheduleAttachement must contain a value.我想做一个自定义验证来检查 bool IsScheduled == true,ScheduleAttachement 必须包含一个值。 If not throw 400 bad request如果不抛出 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 check: less 代码列表 null 或空检查:

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

In your controller layer在你的controller

var emailToCheck = new SendEmail();

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

If you want to add a custom message lookup this answer .如果您想添加自定义消息查找此答案

Edit编辑

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM