C# CustomAttributes:Description、Required 综合使用


/// <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);

转载注明原文地址:https://www.cnblogs.com/Veary/p/14338059.html

上一篇:面向对象与函数式编程的简单案例


下一篇:jquery.validate不使用submit提交,而是使用button按钮提交