.NET 10 C# 14 New Features 新增功能介绍-ASP.NET Core

张开发
2026/4/19 8:06:35 15 分钟阅读

分享文章

.NET 10  C# 14 New Features 新增功能介绍-ASP.NET Core
在以前的版本中Minimal API 默认不会自动执行 DataAnnotations 验证通常需要手动调用 Validator使用 FluentValidation或写 Middleware / Filter而在.NET 10中Minimal API可以自动执行模型验证和 MVC Controller 的行为一致。使用DataAnnotations注解public class UserDto { [Required] public string Name { get; set; } [Range(1,120)] public int Age { get; set; } }Minimal APIapp.MapPost(/users, (UserDto dto) { return Results.Ok(dto); });如果请求{age: 200}系统会自动返回 400{ type: https://tools.ietf.org/html/rfc9110#section-15.5.1, title: One or more validation errors occurred., errors: { Name: [The Name field is required.], Age: [The field Age must be between 1 and 120.] } }这个自动校验的触发机制是这样的ASP.NET Core 会在Endpoint Binding 阶段执行Request Body → Model BindingDataAnnotations Validation如果失败 → 自动返回 400 ValidationProblem如果成功 → 进入 Handler二、新增了对 Server-Sent EventsSSE 的原生支持在 ASP.NET Core 的.NET 10中新增了对Server-Sent EventsSSE的原生支持可以通过TypedResults.ServerSentEvents 直接返回实时数据流。这让Minimal API 实现实时推送变得非常简单无需使用 WebSocket 或 SignalR。一行代码搞定TypedResults.ServerSentEvents()自动设置 Content-Type处理数据流格式处理 Flush示例代码app.MapGet(/time, () { async IAsyncEnumerablestring GetTimeStream() { while (true) { yield return DateTime.Now.ToString(HH:mm:ss); await Task.Delay(1000); } } return TypedResults.ServerSentEvents(GetTimeStream()); });前端JS代码const source new EventSource(/time);source.onmessage (event) {console.log(Server time:, event.data);};同时.NET 10 支持Typed SSE Eventapp.MapGet(/events, () { async IAsyncEnumerableSseItemstring Stream() { while (true) { yield return new SseItemstring( DateTime.Now.ToString(), eventType: time ); await Task.Delay(1000); } } return TypedResults.ServerSentEvents(Stream()); });三、OpenAPI 3.1支持OpenAPI Specification 是 REST API 的行业标准规范。OpenAPI 3.1 的核心变化MiniAPI代码示例var builder WebApplication.CreateBuilder(args); builder.Services.AddOpenApi(); var app builder.Build(); app.MapGet(/stations, () { return new[] { new { Id 1, Name Station A }, new { Id 2, Name Station B } }; }); app.MapOpenApi(); app.Run();访问/openapi/v1.json返回得到OpenAPI 3.1文档。同时YAML也得到了支持在 API 管理和云平台中很多工具更喜欢YAML格式。/openapi/v1.yaml示例返回openapi: 3.1.0 info: title: Charging API version: 1.0.0 paths: /stations: get: responses: 200: description: OK启用YAML输出builder.Services.AddOpenApi(options { options.AddDocumentTransformer((doc, ctx, ct) { doc.Info.Title Charging Platform API; return Task.CompletedTask; }); });

更多文章