C#接口调用前数据有效性所有字段校验
using System.ComponentModel.DataAnnotations;
/// <summary>
/// 自定义实体类
/// </summary>
public class DATAINFO
{
/// <summary>
/// 员工号 入职年月(YYYYMM)+4位流水
/// </summary>
[Required]
public string CODE { get; set; }
/// <summary>
/// 对外接收参数-姓名
/// </summary>
[Required]
public string DESC1 { get; set; }
/// <summary>
/// 对外接收参数-所属部门编码 所属组织编码,对应管理组织中的“组织编码”
/// </summary>
public string DESC83 { get; set; }
/// <summary>
/// 必填校验
/// </summary>
public void Validate()
{
ValidationContext context = new ValidationContext(this, serviceProvider: null, items: null);
List<ValidationResult> results = new List<ValidationResult>();
bool isValid = Validator.TryValidateObject(this, context, results, true);
if (isValid == false)
{
StringBuilder sbrErrors = new StringBuilder();
foreach (var validationResult in results)
{
sbrErrors.Append(string.Format("{0} 字段必填!", validationResult.MemberNames.FirstOrDefault()));
}
throw new ValidationException(sbrErrors.ToString());
}
}
}
使用:
例如:接口调用前的数据有效性校验
List<DATAINFO>.ForEach((p) =>
{
p.Validate();
});