关于 signalr
用于通过 ASP.NET Core SignalR 实现客户端与服务器实时通信的技能,介绍 Hub 和组模式、JWT 查询参数认证、服务集成及连接测试。
主要功能
- 01SignalR Hub 实现模式
- 02基于组的消息路由
- 03强类型 Hub 与客户端接口
- 04JWT 查询参数认证
- 05服务端通知与客户端测试
适用场景
- 01向订阅者广播工作流通知
- 02按 Register 或钱包路由账本事件
- 03将通知逻辑与 Hub 解耦
- 04测试经过认证的 Hub 连接
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ stuartf303/ sorcha --skill signalr安装后在 Claude Code 中输入/signalr确认已加载。
附带文件references/patterns.mdreferences/workflows.md
详细介绍
SignalR 技能
用于实时客户端-服务端通信的 ASP.NET Core SignalR 实现。Sorcha 使用两个 Hub:ActionsHub(Blueprint Service)用于工作流通知,RegisterHub(Register Service)用于账本事件。两者都通过基于组的广播,并使用查询参数中的 JWT 进行身份验证。
快速开始
Hub 实现
// 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);
}
从服务发送
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);
}
}
客户端连接(测试)
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);
核心概念
| 概念 | 用途 | 示例 |
|---|---|---|
| 组 | 将消息路由给订阅者 | wallet:{address}, register:{id}, tenant:{id} |
| 类型化 Hub | 编译时安全性 | Hub<IRegisterHubClient> |
| IHubContext | 从服务发送 | 注入 IHubContext<THub> |
| JWT 身份验证 | 查询参数身份验证 | ?access_token={jwt} |
常见模式
在 Hub 上添加服务抽象层
适用场景: 将业务逻辑与 SignalR 实现解耦
// Interface in Services/Interfaces/
public interface INotificationService
{
Task NotifyActionAvailableAsync(ActionNotification notification, CancellationToken ct = default);
}
// Register in DI
builder.Services.AddScoped<INotificationService, NotificationService>();
在 Program.cs 中注册 Hub
builder.Services.AddSignalR();
// Map after authentication middleware
app.MapHub<ActionsHub>("/actionshub");
app.MapHub<RegisterHub>("/hubs/register");
另请参阅
相关技能
- aspire - 服务编排与配置
- jwt - Hub 连接的身份验证令牌设置
- redis - 用于扩展的 Backplane 配置
- xunit - 集成测试模式
- fluent-assertions - Hub 测试的断言
文档资源
使用 Context7 获取最新的 SignalR 文档。
Context7 使用方法:
- 使用
mcp__context7__resolve-library-id搜索 "signalr aspnetcore" - 优先选择网站文档(ID 以
/websites/开头),而非源代码 - 使用已解析的库 ID,通过
mcp__context7__query-docs查询
库 ID: /websites/learn_microsoft_en-us_aspnet_core (包含 SignalR 的 ASP.NET Core 文档)
推荐查询:
- "SignalR hub groups authentication"
- "SignalR Redis backplane scaling"
- "SignalR strongly typed hubs"
评论
支持 Markdown