.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版本,目前新特性正在持续更新中,还需继续跟着微软进行学习一下。

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

相关推荐
m0_720245019 小时前
QT(四)基本组件
数据库·qt·microsoft
Humbunklung11 小时前
C# WPF 实现读取文件夹中的PDF并显示其页数
pdf·c#·wpf·npoi·gemini·itext
时光追逐者12 小时前
C#/.NET/.NET Core技术前沿周刊 | 第 48 期(2025年7.21-7.27)
c#·.net·.netcore·.net core
蓝点lilac12 小时前
C# 调用邮箱应用发送带附件的邮件
c#·.net
工程师00713 小时前
C#多线程,同步与异步详解
开发语言·c#·多线程·同步·异步编程
王柏龙14 小时前
Entity Framework Core (EF Core) 中Database
数据库·microsoft
ArabySide15 小时前
【Linux】Ubuntu上安装.NET 9运行时与ASP.NET Core项目部署入门
linux·ubuntu·.net
小乖兽技术15 小时前
在 .NET 中使用 Base64 时容易踩的坑总结
开发语言·c#·.net
HANFAN17 小时前
.NET4通过HTTP操作MINIO
.net·minio