/// <summary>
/// 检查返回消息
/// </summary>
public class CheckMessage
{
/// <summary>
/// 是否通过
/// </summary>
public bool IsValid { get; set; }
/// <summary>
/// 错误消息
/// </summary>
public List<string> ErrMessage { get; set; }
}
/// <summary>
/// 数据校验
/// </summary>
public static class ModelCheck
{
/// <summary>
/// 数据校验
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sourceEntity"></param>
/// <returns></returns>
public static CheckMessage VerifyCheck<T>(this T sourceEntity) where T : class
{
CheckMessage checkMessage = new CheckMessage();
checkMessage.IsValid = true;
checkMessage.ErrMessage = new List<string>();
foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
{
RequiredAttribute requiredAttribute = (RequiredAttribute)Attribute.GetCustomAttribute(propertyInfo, typeof(RequiredAttribute));
DescriptionAttribute descriptionAttribute = (DescriptionAttribute)Attribute.GetCustomAttribute(propertyInfo, typeof(DescriptionAttribute));
if (requiredAttribute != null)
{
bool currentProperty = requiredAttribute.IsValid(propertyInfo.GetValue(sourceEntity, null));
checkMessage.IsValid &= currentProperty;
string errMessage = requiredAttribute.ErrorMessage;
if (!currentProperty)
{
if (errMessage == null)
{
errMessage = $"{propertyInfo.Name} 不可以为空";
if (descriptionAttribute != null && !descriptionAttribute.Description.IsNullOrEmpty())
errMessage = $"{propertyInfo.Name}:{descriptionAttribute.Description} 不可以为空";
}
checkMessage.ErrMessage.Add(errMessage);
}
}
}
return checkMessage;
}
}
使用方式
/// <summary>
/// 手机号码
/// </summary>
[Description("手机号码")]
[Required]
public string Msisdn { get; set; }
// 数据验证
CheckMessage checkMessage = req.VerifyCheck();
if (!checkMessage.IsValid)
return Error("数据验证失败", checkMessage);