ASP.NET Core SignalR 新功能
在本文中,我将重点介绍最新的。NET 9 SignalR 更新适用于 ASP.NET Core 9.0。
SignalR Hub 接受基类
SignalRHub类现在可以获取多态类的基类。如下例所示,我可以Animal向 Process方法发送 。在 .NET 9 之前,我们只能传递派生类:Cat和Dog。
/*** My Base Class is Animal ***/
[JsonPolymorphic]
[JsonDerivedType(typeof(Cat), nameof(Cat))]
[JsonDerivedType(typeof(Dog), nameof(Dog))]
private class Animal
{
public string Name { get; set; }
}
/*** CAT derived from Animal ***/
private class Cat : Animal
{
public CatTypes CatType { get; set; }
}
/*** DOG derived from Animal ***/
private class Dog : Animal
{
public DogTypes DogType { get; set; }
}
public class MyHub : Hub
{
/*** We can use the base type Animal here ***/
public void Process(Animal animal)
{
if (animal is Cat) { ... }
else if (animal is Dog) { ... }
}
}
更好的诊断和遥测
微软如今主要专注于 .NET Aspire。因此,SignalR 现在与常用于分布式跟踪的 .NET Activity API 进行了更深入的集成。这项增强功能旨在更好地在.NET Aspire Dashboard中进行监控。支持此功能的方法如下:
1-将这些包添加到您的csproj:
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.9.0" />
2-将以下启动代码添加到您的主机项目:
builder.Services.AddSignalR();
/* After AddSignalR use AddOpenTelemetry() */
builder
.Services
.AddOpenTelemetry()
.WithTracing(tracing =>
{
if (builder.Environment.IsDevelopment())
{
tracing.SetSampler(new AlwaysOnSampler()); //for dev env monitor all traces
}
tracing.AddAspNetCoreInstrumentation();
tracing.AddSource("Microsoft.AspNetCore.SignalR.Server");
});
builder.Services.ConfigureOpenTelemetryTracerProvider(tracing => tracing.AddOtlpExporter());
最后,你会看到SignalR 中心Aspire 仪表板上的事件:
修剪和原生 AOT 支持
使用 .NET 9,修剪和本国的 提前编译是支持。这将提高我们应用程序的性能。为了支持 AOT,您的 SignalR 对象序列化需要为 JSON,并且您必须使用System.Text.Json源代码生成器。此外,在服务器端,您不应该使用 IAsyncEnumerable<T>和 ,ChannelReader<T>其中TValueType 是(struct)作为 Hub 方法参数。还有一个限制;强类型集线器不支持 Native AOT(PublishAot)。并且您应该只使用Task、Task<T>、ValueTask、ValueTask<T>作为async返回类型。
如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。