我一直在尝试在我的ASP.NET Core Web API项目中实现SignalR。我已经遵循了文档上的最低限度的细节来让它工作。当我通过Postman(和Insomnia)连接到集线器时,它说与状态代码101连接(我相信这是预期的?)。但是,OnConnectedAsync方法的重写永远不会命中。
这是Hub:
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();
型
我运行该项目并尝试通过postman与以下对象建立连接:wss://localhost:7090/chat-hub.连接成功,状态代码为101切换协议。那么,为什么没有消息发送,而且当我看到的示例都能从这里工作时,我的集线器中的OnConnectedAsync
内的断点没有被命中。
1条答案
按热度按时间ndh0cuux1#
SignalR协议不仅仅是一个简单的WebSocket连接。要正确测试您的SignalR集线器,您应该使用SignalR客户端。
字符串
有关详细信息,请参阅以下文章。https://medium.com/@krishan-samarawickrama/building-a-real-time-application-with-asp-net-core-signalr-a-comprehensive-guide-874e975377c8