.NET 10 - 尝试一下Minimal Api的Validation新特性

1.简单介绍

2025年11月微软将会发布.NET10,这是LTS(Long Term Support)版本。当前.NET10已经处于Preview4版本,微软对Runtime, Library, SDK, C#, Asp.NET Core, MAUI等都做了很多enhancement。近些年微软对Minimal Api一直在持续地更新。在.NET8中, Minimal Api新增的feature有支持文件上传,同时支持form数据绑定,在.NET10中,Minimal Api支持数据验证,可以对提交的数据(来自Query, Header, Requset Body)进行格式,范围,必填等限制,也可以自定义验证逻辑(通过继承ValidationAttribute或者implement IValidatableObject接口来实现)。

这边将尝试一下.NET 10中Minimal Api Validation新特性

2.具体说明

2.1 创建Minimal Api项目

  1. 基于.NET10创建Minimal Api项目

  2. 在项目文件中,添加InterceptorsNamesapces

复制代码
<InterceptorsNamespaces>$(InterceptorsNamespaces);Microsoft.AspNetCore.Http.Validation.Generated</InterceptorsNamespaces>
  1. 在Program中,添加如下语句

    builder.Services.AddValidation();

2.2 定义todo类

分别对Name和DueDate property进行限制,使用的attribute都是来自namespace System.ComponentModel.DataAnnotations的,代码如下

复制代码
    public class Todo
    {
        [Required]
        public string Name { get; set; } = string.Empty;

        [Range(typeof(DateTime), "5/1/2025", "5/26/2025", ErrorMessage = "Value for {0} must be between {1} and {2}")]
        public DateTime DueDate { get; set; } = DateTime.Now.Add(TimeSpan.FromDays(1));
    }

2.3 尝试Validation

  1. 添加一个post endpoint,并且设定Todo类型的参数,使用[FromForm] attribute标注一下,

    app.MapPost("/todos", ([FromForm] Todo todo) => todo);

  2. 添加一个get endpoint,客户端可以获取到表单。当表单提交时,form字段将会绑定到Todo参数中

    app.MapGet("/todoform", (HttpContext context, IAntiforgery antiforgery) =>
    {
    var token = antiforgery.GetAndStoreTokens(context);
    var html = $$"""
    <html>
    <head>
    <style>
    body {
    font-family: Arial, sans-serif;
    margin: 20px;
    }

    复制代码
     						form {
     							max-width: 400px;
     							margin: 0 auto;
     						}
    
     						...
     					</style>
     				</head>
     				<body>
     					<form action="/todos" method="POST" enctype="multipart/form-data">
     						<input name="{{token.FormFieldName}}" type="hidden" value="{{token.RequestToken}}" />
     						<label for="name">Todo Name:</label>
     						<input type="text" name="name" />
     						<label for="dueDate">Due Date:</label>
     						<input type="date" name="dueDate" />
     						<input type="submit" />
     					</form>
     				</body>
     			</html>
     		""";
     return Results.Content(html, "text/html");

    });

2.4 运行一下

  1. 客户端通过访问上面步骤得到表单后,如果没有输入Todo Name的值,点击Submit按钮提交后,页面会显示Required Validation相关错误信息,如下图所示,
  1. 如果设定的Due Date的值超出2025/5/1-2025/5/26这个范围,则页面也会显示相关的验证错误信息,

note, Minimal Api的数据验证,也支持嵌套验证的,

比如Todo类包含一个Approver类型的property,如下图所示,这种嵌套数据验证也是支持的

3.总结

本文简单记录了一下.NET10中Minimal Api的数据验证的使用过程。如果.NET10自带的Validation不能满足业务需求,也可以通过继承ValidationAttribute或者implement IValidatableObject接口来进行定制的。.NET10是LTS版本,目前新特性正在持续更新中,还需继续跟着微软进行学习一下。

本文如果哪里有错误,麻烦告之,谢谢谢谢!

相关推荐
hixiong12328 分钟前
C# OpenvinoSharp部署DDDDOCR验证码识别模型
opencv·c#·ocr·openvino
唐青枫1 小时前
C#.NET ConcurrentBag<T> 设计原理与使用场景
c#·.net
玩泥巴的10 小时前
飞书 .NET SDK 事件处理的幂等性与去重机制
c#·.net·二次开发·飞书
在路上看风景10 小时前
3.2 FileStream
c#
zwm26988881510 小时前
6号楼 部分声光24v电压达不到,显示11v
c#
喵叔哟11 小时前
20.部署与运维
运维·docker·容器·.net
椒颜皮皮虾14 小时前
TensorRtSharp:在 C# 世界中释放 GPU 推理的极致性能
c#·tensorrt
行止9514 小时前
WinForms 彻底隐藏 滚动条的终极解决方案
c#
bugcome_com15 小时前
WPF样式进阶实战:外置样式+MVVM主题切换+样式优先级全解析
c#·.net·wpf
时光追逐者16 小时前
TIOBE 公布 C# 是 2025 年度编程语言
开发语言·c#·.net·.net core·tiobe