.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; } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
2023-01-26 C#异步方法中Task.WhenAll的使用