如何在ASP.NET Core 2.2中使用来自不同托管项目的共享SignalR Hub [英] How to use shared SignalR Hub from different hosted project in ASP.NET Core 2.2

查看:108
本文介绍了如何在ASP.NET Core 2.2中使用来自不同托管项目的共享SignalR Hub的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ASP.NET Core 2.2构建一个项目.主要解决方案包含多个项目,其中包括API,Web和其他类库.

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.

我们已经使用SignalR来显示API项目和Web项目之间的共享消息/通知.例如,从API添加新的员工记录应调用SignalR Hub,所有Web客户端都应收到通知.

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

流量:

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没有收到任何通知.我认为问题在于它为每个项目创建了两个单独的连接,但是处理这种情况的最佳方法是什么?

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?

编辑:在此api代码中,我可以获得连接ID和状态为已连接",但是Web仍未收到任何通知.还尝试了connection.InvokeAsync

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();

推荐答案

您可以将HubContext注入API项目中的控制器中,然后尝试点击"InvokeAsync"

you can inject your HubContext into your controller in API project and try hitting 'InvokeAsync'

这篇关于如何在ASP.NET Core 2.2中使用来自不同托管项目的共享SignalR Hub的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆