I'm working with a project built with ASP.NET Core 2.2. The main solution contains multiple projects, which includes API, web and other class libraries.
We've used SignalR to displaying shared messages/notifications between the API project and the web project. For example, adding a new employee record from an API should call SignalR Hub and all the web client should received the notification.
Here is the current structure of our project
|- API
|- Hub_ClassLibrary
|- Services
|- Web
Flow:
Web > services > Hub
API > services > Hub
Hub:
public class NotificationHub : Hub
{
public async Task SendNotification(List<DocumentHistoryModel> notifications)
{
await Clients.All.SendAsync(Constants.ReceiveNotification, notifications);
}
}
Web startup class:
app.UseSignalR(routes =>
{
routes.MapHub<NotificationHub>("/notificationHub");
});
API startup class
app.UseSignalR(routes =>
{
routes.MapHub<NotificationHub>("/notificationHub");
});
Service
private readonly IHubContext<NotificationHub> _hubContext;
public MyService(IHubContext<NotificationHub> hubContext)
{
_hubContext = hubContext;
}
await _hubContext.Clients.All.SendAsync(ReceiveNotification, notifications);
The issue is, I can send and receive notifications from web, but from api call, web doesn't get any notification. I think problem is it creates two separate connections for each project, but then what is the best way to handle this kind of scenario?
Edit: I can get connection id and state "connected" in this api code, however, web is still not receiving any notification. Also tried 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
andAPI
? – WhollyAzure SignalR
so you can redirect to it in your both cases. – WhollyRedis
to communicate with both of them. – WhollyRabitMQ
/Redis
): there should be only one Hub, and a service subscribes some event, your Web & API can publish that type of event. And then the Hub will push notifications to clients. Or an easy way is (maybe not elegant) , replace the second hub with a HubClient, and push notification to Hub and then push notifications to other clients – Trifle