signalr
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSignalR Skill
SignalR Skill
ASP.NET Core SignalR implementation for real-time client-server communication. Sorcha uses two hubs: (Blueprint Service) for workflow notifications and (Register Service) for ledger events. Both use group-based broadcasting with JWT authentication via query parameters.
ActionsHubRegisterHub基于ASP.NET Core SignalR的实时客户端-服务器通信实现。Sorcha使用两个Hub:用于工作流通知的(蓝图服务)和用于账本事件的(注册服务)。两者均通过查询参数的JWT认证实现基于群组的广播功能。
ActionsHubRegisterHubQuick Start
快速开始
Hub Implementation
Hub实现
csharp
// Strongly-typed hub with client interface
public class RegisterHub : Hub<IRegisterHubClient>
{
public async Task SubscribeToRegister(string registerId)
{
await Groups.AddToGroupAsync(Context.ConnectionId, $"register:{registerId}");
}
}
public interface IRegisterHubClient
{
Task RegisterCreated(string registerId, string name);
Task TransactionConfirmed(string registerId, string transactionId);
}csharp
// 带客户端接口的强类型Hub
public class RegisterHub : Hub<IRegisterHubClient>
{
public async Task SubscribeToRegister(string registerId)
{
await Groups.AddToGroupAsync(Context.ConnectionId, $"register:{registerId}");
}
}
public interface IRegisterHubClient
{
Task RegisterCreated(string registerId, string name);
Task TransactionConfirmed(string registerId, string transactionId);
}Sending from Services
从服务端发送消息
csharp
public class NotificationService
{
private readonly IHubContext<ActionsHub> _hubContext;
public async Task NotifyActionConfirmedAsync(ActionNotification notification, CancellationToken ct)
{
await _hubContext.Clients
.Group($"wallet:{notification.WalletAddress}")
.SendAsync("ActionConfirmed", notification, ct);
}
}csharp
public class NotificationService
{
private readonly IHubContext<ActionsHub> _hubContext;
public async Task NotifyActionConfirmedAsync(ActionNotification notification, CancellationToken ct)
{
await _hubContext.Clients
.Group($"wallet:{notification.WalletAddress}")
.SendAsync("ActionConfirmed", notification, ct);
}
}Client Connection (Testing)
客户端连接(测试)
csharp
var connection = new HubConnectionBuilder()
.WithUrl($"{baseUrl}/actionshub?access_token={jwt}")
.Build();
connection.On<ActionNotification>("ActionConfirmed", notification => { /* handle */ });
await connection.StartAsync();
await connection.InvokeAsync("SubscribeToWallet", walletAddress);csharp
var connection = new HubConnectionBuilder()
.WithUrl($"{baseUrl}/actionshub?access_token={jwt}")
.Build();
connection.On<ActionNotification>("ActionConfirmed", notification => { /* 处理逻辑 */ });
await connection.StartAsync();
await connection.InvokeAsync("SubscribeToWallet", walletAddress);Key Concepts
核心概念
| Concept | Usage | Example |
|---|---|---|
| Groups | Route messages to subscribers | |
| Typed Hubs | Compile-time safety | |
| IHubContext | Send from services | Inject |
| JWT Auth | Query parameter auth | |
| 概念 | 用途 | 示例 |
|---|---|---|
| Groups | 向订阅者路由消息 | |
| Typed Hubs | 编译时类型安全 | |
| IHubContext | 从服务端发送消息 | 注入 |
| JWT Auth | 查询参数认证 | |
Common Patterns
常见模式
Service Abstraction Over Hub
基于Hub的服务抽象
When: Decoupling business logic from SignalR implementation
csharp
// Interface in Services/Interfaces/
public interface INotificationService
{
Task NotifyActionAvailableAsync(ActionNotification notification, CancellationToken ct = default);
}
// Register in DI
builder.Services.AddScoped<INotificationService, NotificationService>();适用场景: 将业务逻辑与SignalR实现解耦
csharp
// 接口定义在Services/Interfaces/目录下
public interface INotificationService
{
Task NotifyActionAvailableAsync(ActionNotification notification, CancellationToken ct = default);
}
// 在依赖注入中注册
builder.Services.AddScoped<INotificationService, NotificationService>();Hub Registration in Program.cs
在Program.cs中注册Hub
csharp
builder.Services.AddSignalR();
// Map after authentication middleware
app.MapHub<ActionsHub>("/actionshub");
app.MapHub<RegisterHub>("/hubs/register");csharp
builder.Services.AddSignalR();
// 在认证中间件之后映射Hub
app.MapHub<ActionsHub>("/actionshub");
app.MapHub<RegisterHub>("/hubs/register");See Also
相关链接
- patterns - Hub patterns, group routing, typed clients
- workflows - Testing, scaling, authentication setup
- patterns - Hub模式、群组路由、强类型客户端
- workflows - 测试、扩容、认证配置
Related Skills
相关技能
- aspire - Service orchestration and configuration
- jwt - Authentication token setup for hub connections
- redis - Backplane configuration for scaling
- xunit - Integration testing patterns
- fluent-assertions - Test assertions for hub tests
- aspire - 服务编排与配置
- jwt - Hub连接的认证令牌配置
- redis - 用于扩容的背板配置
- xunit - 集成测试模式
- fluent-assertions - Hub测试的断言工具
Documentation Resources
文档资源
Fetch latest SignalR documentation with Context7.
How to use Context7:
- Use to search for "signalr aspnetcore"
mcp__context7__resolve-library-id - Prefer website documentation (IDs starting with ) over source code
/websites/ - Query with using the resolved library ID
mcp__context7__query-docs
Library ID: (ASP.NET Core docs including SignalR)
/websites/learn_microsoft_en-us_aspnet_coreRecommended Queries:
- "SignalR hub groups authentication"
- "SignalR Redis backplane scaling"
- "SignalR strongly typed hubs"
使用Context7获取最新的SignalR文档。
如何使用Context7:
- 使用搜索"signalr aspnetcore"
mcp__context7__resolve-library-id - 优先选择网站文档(以开头的ID)而非源代码
/websites/ - 使用解析后的库ID,通过进行查询
mcp__context7__query-docs
库ID: (包含SignalR的ASP.NET Core文档)
/websites/learn_microsoft_en-us_aspnet_core推荐查询:
- "SignalR Hub群组认证"
- "SignalR Redis背板扩容"
- "SignalR强类型Hub"