WebAPI ModelValidata(模型验证)——DataAnnotations 解析

 爱做一个新的项目,在该项目中的 WebAPI 中对数据的验证用到了 ModelValidata,

以前也没有用到过,也不是很熟悉,在查看了一些资料和代码后稍有了解,这里记录下来。

这里主要介绍的是 System.ComponentModel.DataAnnotations 下的一些验证方式的使用。

一、在 Filter 中统一对验证结果返回

public class WebAPIActionFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            base.OnActionExecuting(actionContext);

            // 模型验证
            if (actionContext.ModelState.IsValid == false)
            {
                actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
            }
        }
    }

二、验证方式解析

在实体类中对需要验证的字段添加验证方式,这里以一个 “UserDTO” 实体类作为研究对象。

    public class UserDTO
    {
        [Required(ErrorMessage = "账户不能为空")]
        public string Account { get; set; }

        [Required(ErrorMessage = "密码不能为空")]
        [StringLength(18, MinimumLength = 6, ErrorMessage = "密码长度为 6-18 个字符")]
        public string Password { get; set; }

        /// <summary>
        /// 姓名
        /// </summary>
        [Required(ErrorMessage ="姓名不能为空")]
        [RegularExpression(@"\w{2,15}", ErrorMessage = "名称应为2-15长度的字母组合")]
        public string Name { get; set; }/// <summary>
        /// 手机
        /// </summary>
        [RegularExpression(@"\n{11}", ErrorMessage = "手机号码为11位数字")]
        [Phone]
        public string Mobile { get; set; }

        /// <summary>
        /// 电话
        /// </summary>
        [MaxLength(12,ErrorMessage ="电话号码最长为12位")]
        [MinLength(10, ErrorMessage = "电话号码最短为10位")]
        public string Telephone { get; set; }

        /// <summary>
        /// 年龄
        /// </summary>
        [Range(0,100)]
        public int Age { get; set; }

        /// <summary>
        /// 链接
        /// </summary>
        [Url]
        public string Url { get; set; }

        /// <summary>
        /// 部门类型
        /// </summary>
        [EnumDataType(UnitTypeEnum)]
        public string UnitType { get; set; }

        /// <summary>
        /// email
        /// </summary>
        [EmailAddress]
        public string Email { get; set; }
    }

上面列出的验证有:

1、Required:该值指示是否允许为空字符串;

2、StringLength:该值指示字符串最大和最小长度;

3、RegularExpression:用来验证数据字段值的正则表达式;

4、Phone:用来验证手机号码;

5、MaxLength:验证数据的最大长度;

6、MinLength:验证数据的最小长度;

7、Range:使用指定的最小值和最大值;

8、Url:验证指定的 URL 的格式;

9、EnumDataType:启用 .NET Framework 枚举,以映射到数据列;

10、EmailAddress:确定指定的值是否与有效的电子邮件地址的模式相匹配;

 这里列出的是一些常见的。

posted @ 2018-12-07 13:45  漠里  阅读(733)  评论(0编辑  收藏  举报