我一直在尝试将 SignalR 实现到我的 ASP.NET Core Web API 项目中。我已遵循文档中的最低限度详细信息以使其正常工作。当我通过 Postman(和 Insomnia)连接到集线器时,它显示已连接状态代码 101(我相信这是预期的?)。但是,OnConnectedAsync 方法的重写永远不会被命中。
这是中心:
using Microsoft.AspNetCore.SignalR;
namespace SignalRTest
{
public class ChatHub : Hub
{
public override async Task OnConnectedAsync()
{
await Clients.All.SendAsync("method", "someone connected");
}
}
}
Program.cs 文件与模板文件完全相同,只是添加了
builder.Services.AddSignalR()
和 app.MapHub<ChatHub>("chat-hub")
:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSignalR();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.MapHub<ChatHub>("chat-hub");
app.Run();
我运行该项目并尝试通过邮递员进行连接:wss://localhost:7090/chat-hub。连接成功,状态代码为 101 切换协议。那么,为什么没有发送任何消息,并且我的集线器中的
OnConnectedAsync
内的断点没有被命中,而我看到的所有示例都可以从这里开始工作。