原文 | Daniel Roth
翻译 | 郑子铭
.NET 7 预览版 1 现已推出!这是 .NET 下一个主要版本的第一个预览版,其中将包括使用 ASP.NET Core 进行 Web 开发的下一波创新。
在 .NET 7 中,我们计划对 ASP.NET Core 进行广泛投资。以下是我们计划重点关注的一些领域:
有关为 .NET 7 计划的特定 ASP.NET Core 工作的更多详细信息,请参阅 GitHub 上针对 .NET 7 的完整 ASP.NET Core 路线图。
.NET 7 Preview 1 是众多 .NET 7 预览版中的第一个,为 2022 年 11 月的 .NET 7 版本做准备。
我在最近一集 On .NET 中加入了 James Montemagno,以分解 .NET 7 和 .NET 7 中的 ASP.NET Core 中的所有内容:
以下是此预览版中新增内容的摘要:
要开始使用 .NET 7 Preview 1 中的 ASP.NET Core,请安装 .NET 7 SDK。
如果您在 Windows 上使用 Visual Studio,我们建议安装最新的 Visual Studio 2022 预览版。 Visual Studio for Mac 对 .NET 7 预览的支持尚不可用,但即将推出。
要安装最新的 .NET WebAssembly 构建工具,请从提升的命令提示符处运行以下命令:
dotnet workload install wasm-tools
要将现有的 ASP.NET Core 应用从 .NET 6 升级到 .NET 7 Preview 1:
另请参阅 .NET 7 的 ASP.NET Core 中的重大更改的完整列表。
您现在可以使用 IFormFile 和 IFormFileCollection 在最少的 API 中处理文件上传:
app.MapPost("/upload", async(IFormFile file) =>
{
using var stream = System.IO.File.OpenWrite("upload.txt");
await file.CopyToAsync(stream);
});
app.MapPost("/upload", async (IFormFileCollection myFiles) => { ... });
将此功能与身份验证一起使用需要防伪支持,但尚未实现。我们的 .NET 7 路线图包含对最小 API 的防伪支持。当请求包含 Authorization 标头、客户端证书或 cookie 标头时,绑定到 IFormFile 或 IFormFileCollection 当前被禁用。我们将在完成防伪支持工作后立即解决此限制。
感谢 @martincostello 贡献此功能。
您现在可以将请求正文绑定为 Stream 或 PipeReader,以有效地支持用户必须摄取数据并将其存储到 blob 存储或将数据排队到队列提供程序(Azure 队列等)以供以后处理的场景工作者或云功能。以下示例显示了如何使用新绑定:
app.MapPost("v1/feeds", async (QueueClient queueClient, Stream body, CancellationToken cancellationToken) =>
{
await queueClient.CreateIfNotExistsAsync(cancellationToken: cancellationToken);
await queueClient.SendMessageAsync(await BinaryData.FromStreamAsync(body), cancellationToken: cancellationToken);
});
使用 Stream 或 PipeReader 时,需要考虑以下几点:
我们正在引入一个新的更简洁的 API,ConfigureRouteHandlerJsonOptions,为最小的 API 端点配置 JSON 选项。这个新的 API 避免了与 Microsoft.AspNetCore.Mvc.JsonOptions 的混淆。
var builder = WebApplication.CreateBuilder(args);
builder.Services.ConfigureRouteHandlerJsonOptions(options =>
{
//Ignore Cycles
options.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
});
感谢@mehmetakbulut 的贡献,我们为 SignalR 添加了一个新的客户端源生成器。
SignalR 客户端源生成器根据您定义的接口生成强类型的发送和接收代码。您可以在客户端上重用来自强类型 SignalR 集线器的相同接口来代替松散类型的 .On("methodName", ...) 方法。同样,您的集线器可以为其方法实现一个接口,并且客户端可以使用该相同接口来调用集线器方法。
要使用 SignalR 客户端源生成器:
[AttributeUsage(AttributeTargets.Method)]
internal class HubServerProxyAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Method)]
internal class HubClientProxyAttribute : Attribute
{
}
internal static partial class MyCustomExtensions
{
[HubClientProxy]
public static partial IDisposable ClientRegistration<T>(this HubConnection connection, T provider);
[HubServerProxy]
public static partial T ServerProxy<T>(this HubConnection connection);
}
public interface IServerHub
{
Task SendMessage(string message);
Task<int> Echo(int i);
}
public interface IClient
{
Task ReceiveMessage(string message);
}
public class Client : IClient
{
// Equivalent to HubConnection.On("ReceiveMessage", (message) => {});
Task ReceiveMessage(string message)
{
return Task.CompletedTask;
}
}
HubConnection connection = new HubConnectionBuilder().WithUrl("...").Build();
var stronglyTypedConnection = connection.ServerProxy<IServerHub>();
var registrations = connection.ClientRegistration<IClient>(new Client());
await stronglyTypedConnection.SendMessage("Hello world");
var echo = await stronglyTypedConnection.Echo(10);
我们启用了定义一个可为空的页面或视图模型来改进在 ASP.NET Core 应用中使用空状态检查时的体验:
@model Product?
当模型验证生成 ModelErrorDictionary 时,默认情况下它将使用属性名称作为错误键(“MyClass.PropertyName”)。模型属性名称通常是一个实现细节,这会使它们难以从单页应用程序中处理。您现在可以将验证配置为使用相应的 JSON 属性名称,而不是使用新的 SystemTextJsonValidationMetadataProvider(或使用 Json.NET 时的 NewtonsoftJsonValidationMetadataProvider)。
services.AddControllers(options =>
{
options.ModelMetadataDetailsProviders.Add(new SystemTextJsonValidationMetadataProvider())
});
我们清理了 dotnet watch 的控制台输出,以更好地与 ASP.NET Core 的注销保持一致,并在😮表情符号😍.中脱颖而出。
以下是新输出的示例:
C:BlazorApp> dotnet watch
dotnet watch 🔥 Hot reload enabled. For a list of supported edits, see https://aka.ms/dotnet/hot-reload.
💡 Press "Ctrl + R" to restart.
dotnet watch 🔧 Building...
Determining projects to restore...
All projects are up-to-date for restore.
You are using a preview version of .NET. See: https://aka.ms/dotnet-support-policy
BlazorApp -> C:UsersdarothDesktopBlazorAppbinDebugnet7.0BlazorApp.dll
dotnet watch 🚀 Started
info: Microsoft.Hosting.Lifetime[14]
Now listening on: https://localhost:7148
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:5041
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: C:UsersdarothDesktopBlazorApp
dotnet watch ⌚ File changed: .PagesIndex.razor.
dotnet watch 🔥 Hot reload of changes succeeded.
info: Microsoft.Hosting.Lifetime[0]
Application is shutting down...
dotnet watch 🛑 Shutdown requested. Press Ctrl+C again to force exit.
通过将 DOTNET_WATCH_RESTART_ON_RUDE_EDIT 环境变量设置为 true,将 dotnet watch 配置为始终在不提示粗鲁编辑(无法热重新加载的编辑)的情况下重新启动。
您现在可以将服务注入 Blazor 中的自定义验证属性。 Blazor 将设置 ValidationContext,以便它可以用作服务提供者。
public class SaladChefValidatorAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var saladChef = validationContext.GetRequiredService<SaladChef>();
if (saladChef.ThingsYouCanPutInASalad.Contains(value.ToString()))
{
return ValidationResult.Success;
}
return new ValidationResult("You should not put that in a salad!");
}
}
// Simple class configured as a service for dependency injection
public class SaladChef
{
public string[] ThingsYouCanPutInASalad = { "Strawberries", "Pineapple", "Honeydew", "Watermelon", "Grapes" };
}
感谢@MariovanZeist 的贡献!
我们对 HTTP/2 和 HTTP/3 的标头解析和写入性能进行了多项改进。有关详细信息,请参阅以下拉取请求:
gRPC JSON 转码允许 gRPC 服务像 RESTful HTTP API 一样使用。配置完成后,gRPC JSON 转码允许您使用熟悉的 HTTP 概念调用 gRPC 方法:
当然 gRPC 也可以继续使用。用于 gRPC 服务的 RESTful API。没有重复!
ASP.NET Core 使用名为 gRPC HTTP API 的库对此功能提供实验性支持。对于 .NET 7,我们计划将此功能作为 ASP.NET Core 的受支持部分。此功能尚未包含在 .NET 7 中,但您可以试用现有的实验包。有关更多信息,请参阅 gRPC HTTP API 入门文档。
我们希望您喜欢 .NET 7 中的 ASP.NET Core 预览版,并且您对我们的 .NET 7 路线图和我们一样兴奋!我们很想听听您对此版本的体验以及您对路线图的看法。通过在 GitHub 上提交问题并评论路线图问题,让我们知道您的想法。
感谢您试用 ASP.NET Core!
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有