在 ASP.NET Core 6 Web API 项目中,添加 SignalR 和 SignalR.Client NuGet 包。
在 Startup.cs 的 ConfigureServices 方法中添加以下代码:
services.AddSignalR();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub("/myHub"); // 添加 SignalR Hub
});
public class MyHub : Hub
{
public async Task CallClient(string connectionId, string message)
{
return await Clients.Client(connectionId).SendAsync("ReceiveMessage", message);
}
}
[ApiController]
[Route("[controller]")]
public class MyController : ControllerBase
{
private readonly HubConnection _hubConnection;
public MyController(IHubConnectionFactory hubConnectionFactory)
{
_hubConnection = hubConnectionFactory.CreateHubConnection();
}
[HttpGet]
public async Task GetAsync()
{
await _hubConnection.StartAsync();
var connectionId = await _hubConnection.InvokeAsync("GetConnectionId");
var result = await _hubConnection.InvokeAsync("CallClient", connectionId, "Hello, client!");
return result;
}
}
注意:在此示例中,使用了 IHubConnectionFactory 来创建 HubConnection 实例,以便在测试时轻松地模拟 SignalR 连接。