【发布时间】:2020-05-07 10:54:01
【问题描述】:
我正在处理一个使用 ASP.NET Core 2.2 构建的项目。主要解决方案包含多个项目,其中包括 API、Web 和其他类库。
我们使用 SignalR 来显示 API 项目和 Web 项目之间的共享消息/通知。例如,从 API 添加新员工记录应调用 SignalR Hub,并且所有 Web 客户端都应收到通知。
这是我们项目的当前结构
|- API
|- Hub_ClassLibrary
|- Services
|- Web
流程:
Web > services > Hub
API > services > Hub
枢纽:
public class NotificationHub : Hub
{
public async Task SendNotification(List<DocumentHistoryModel> notifications)
{
await Clients.All.SendAsync(Constants.ReceiveNotification, notifications);
}
}
网页启动类:
app.UseSignalR(routes =>
{
routes.MapHub<NotificationHub>("/notificationHub");
});
API 启动类
app.UseSignalR(routes =>
{
routes.MapHub<NotificationHub>("/notificationHub");
});
服务
private readonly IHubContext<NotificationHub> _hubContext;
public MyService(IHubContext<NotificationHub> hubContext)
{
_hubContext = hubContext;
}
await _hubContext.Clients.All.SendAsync(ReceiveNotification, notifications);
问题是,我可以从 web 发送和接收通知,但是从 api 调用,web 没有收到任何通知。我认为问题在于它为每个项目创建了两个单独的连接,但是处理这种情况的最佳方法是什么?
编辑:我可以在这个 api 代码中获取连接 ID 和状态“已连接”,但是,网络仍然没有收到任何通知。也试过connection.InvokeAsync
var connection = new HubConnectionBuilder()
.WithUrl("https://localhost:44330/notificationhub")
.Build();
connection.StartAsync().ContinueWith(task =>
{
if (task.IsFaulted)
{
}
else
{
connection.SendAsync("UpdateDashboardCount", "hello world");
}
}).Wait();
【问题讨论】:
-
他们共享同一个主机吗?
Web和API? -
不,@Kiril1512 的主机不同
-
两者的主机不同:那么会有两个集线器吗? IMO 最好只有一个 Hub: 1. 创建一个 HubClient 将通知推送到 Hub? 1. 或者作为替代,使用RabbitMQ/Redis sub/pub之类的sub/pub方式?
-
@itminus, 所以会有两个集线器? 类库中只有一个集线器。但是想在具有相同数据库的不同项目中使用。不知道如何创建这样的机制。
-
@Div 您可以选择使用
Azure SignalR,以便在两种情况下都可以重定向到它。
标签: c# asp.net-core signalr asp.net-core-2.2