.NET 8 的新增功能-数据验证

1.概要

在.NET8中C#的新增特性,System.ComponentModel.DataAnnotations 命名空间包括用于云原生服务中的验证场景的新数据验证特性。 虽然预先存在的 DataAnnotations 验证程序适用于典型的 UI 数据输入验证(例如窗体上的字段),但新特性旨在验证非用户输入数据,例如配置选项。 除了新特性之外,还向 RangeAttribute 和 RequiredAttribute 类型添加了新属性。

新的 API说明
RangeAttribute.MinimumIsExclusive RangeAttribute.MaximumIsExclusive 指定边界是否包含在允许的范围内。
System.ComponentModel.DataAnnotations.LengthAttribute 指定字符串或集合的下界和上界。 例如,[Length(10, 20)] 要求集合中至少有 10 个元素,最多有 20 个元素。
System.ComponentModel.DataAnnotations.Base64StringAttribute 验证字符串是有效的 Base64 表示形式。
System.ComponentModel.DataAnnotations.AllowedValuesAttribute System.ComponentModel.DataAnnotations.DeniedValuesAttribute 分别指定允许列表和拒绝列表。 例如,[AllowedValues("apple", "banana", "mango")]。

 

 

2、测试

新建一个webapi项目 ,新建一个model  EmployeeModel.cs

复制代码
using System.ComponentModel.DataAnnotations;

namespace WebApplication2.Model
{
    public class EmployeeModel
    {
        /// <summary>
        /// 员工id,Attribute含义:限制id的范围0~int最大值如果不在这个范围内则抛出异常
        /// </summary>
        [Range(0, int.MaxValue)]
        public int Id { get; set; }

        /// <summary>
        /// 员工名称,Attribute含义:限制Name不可以为president(总统),否则抛出ErrorMessage的内容。
        /// </summary>
        [DeniedValues("president")]
        public string Name { get; set; }

        /// <summary>
        /// 年龄 Attribute含义:限制Age的范围0~150岁最大值如果不在这个范围内则抛出异常
        /// </summary>
        [Range(0, 150)]
        public int Age { get; set; }

        //Required Attribute含义:Email字段不能为空(或验证失败),如果为空则抛出ErrorMessage的内容。
        [Required(AllowEmptyStrings = false, ErrorMessage = "邮件字段内容异常请检查!")]
        public string Email { get; set; }

        /// <summary>
        /// 部门,Attribute含义:假设现在只有两个部门,设置值的时候只允许这两个值的出现。否则抛出ErrorMessage的内容。
        /// </summary>
        [AllowedValues("HR", "Develop")]
        public string Department { get; set; }

        /// <summary>
        /// 下属id,Attribute含义:每个员工都有可能有下属,下属最少是1人最多是100人。否则抛出ErrorMessage的内容。
        /// </summary>
        [Length(1, 2)]
        public int[] Underlings { get; set; }

        //Attribute含义:token必须以base64的形式表达。否则抛出ErrorMessage的内容。
        [Base64String]
        public string Token { get; set; }
    }
}
复制代码

 

3、验证

复制代码
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Xml.Linq;
using WebApplication2.Model;
using static System.Net.Mime.MediaTypeNames;

namespace WebApplication2.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class HomeController : ControllerBase
    {
        [HttpGet]
        public EmployeeModel Index()
        {
            EmployeeModel employeeModel = new EmployeeModel()
            {
                Id = -1,
                Name = "president",
                Age = -2,
                Email = "",
                Department = "",
                Underlings = new int[4] { 1, 2, 3, 4 },
                Token = "123"
            };

            if(ChangedAction(employeeModel))
            {
               
            }


            return employeeModel;


        }

        /// <summary>
        /// 验证
        /// </summary>
        /// <param name="employeeModel"></param>
        /// <returns></returns>
        private bool ChangedAction(EmployeeModel employeeModel)
        {
            ValidationContext context = new ValidationContext(employeeModel, null, null);

            List<ValidationResult> validationResults = new List<ValidationResult>();

            bool valid = Validator.TryValidateObject(employeeModel, context, validationResults, true);

            if (!valid)
            {
                foreach (ValidationResult validationResult in validationResults)
                {
                    Debug.WriteLine(validationResult.ErrorMessage);
                    //MessageBox.Show(validationResult.ErrorMessage);
                }
                return false;
            }
            return true;
        }
    }
}
复制代码

 

posted @   ziff123  阅读(106)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
历史上的今天:
2023-01-26 C#异步方法中Task.WhenAll的使用
点击右上角即可分享
微信分享提示