signalr

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

SignalR Skill

SignalR Skill

ASP.NET Core SignalR implementation for real-time client-server communication. Sorcha uses two hubs:
ActionsHub
(Blueprint Service) for workflow notifications and
RegisterHub
(Register Service) for ledger events. Both use group-based broadcasting with JWT authentication via query parameters.
基于ASP.NET Core SignalR的实时客户端-服务器通信实现。Sorcha使用两个Hub:用于工作流通知的
ActionsHub
(蓝图服务)和用于账本事件的
RegisterHub
(注册服务)。两者均通过查询参数的JWT认证实现基于群组的广播功能。

Quick 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

核心概念

ConceptUsageExample
GroupsRoute messages to subscribers
wallet:{address}
,
register:{id}
,
tenant:{id}
Typed HubsCompile-time safety
Hub<IRegisterHubClient>
IHubContextSend from servicesInject
IHubContext<THub>
JWT AuthQuery parameter auth
?access_token={jwt}
概念用途示例
Groups向订阅者路由消息
wallet:{address}
,
register:{id}
,
tenant:{id}
Typed Hubs编译时类型安全
Hub<IRegisterHubClient>
IHubContext从服务端发送消息注入
IHubContext<THub>
JWT Auth查询参数认证
?access_token={jwt}

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:
  1. Use
    mcp__context7__resolve-library-id
    to search for "signalr aspnetcore"
  2. Prefer website documentation (IDs starting with
    /websites/
    ) over source code
  3. Query with
    mcp__context7__query-docs
    using the resolved library ID
Library ID:
/websites/learn_microsoft_en-us_aspnet_core
(ASP.NET Core docs including SignalR)
Recommended Queries:
  • "SignalR hub groups authentication"
  • "SignalR Redis backplane scaling"
  • "SignalR strongly typed hubs"
使用Context7获取最新的SignalR文档。
如何使用Context7:
  1. 使用
    mcp__context7__resolve-library-id
    搜索"signalr aspnetcore"
  2. 优先选择网站文档(以
    /websites/
    开头的ID)而非源代码
  3. 使用解析后的库ID,通过
    mcp__context7__query-docs
    进行查询
库ID:
/websites/learn_microsoft_en-us_aspnet_core
(包含SignalR的ASP.NET Core文档)
推荐查询:
  • "SignalR Hub群组认证"
  • "SignalR Redis背板扩容"
  • "SignalR强类型Hub"