从另一个项目的 API 调用 SignalR - 没有错误也没有通知

Calling SignalR from API at another project - No error nor notification

我有一个与 SignalR 集成的网站。它运行良好,并且有一个按钮可以向所有在线的客户端发送弹出通知。当我点击按钮时效果很好。

我的 API 在另一个项目中,但在同一个解决方案中。我想通过从 API 端调用来发送上述通知。基本上,移动应用程序会向 API 发送请求,然后 API 会向所有在线 Web 客户端发送通知。

下面的代码运行并且没有给出通知也没有任何错误。

这基本上是正确的吗?感谢您的帮助

API 代码(在 WebAPI 项目中)

[HttpGet]
public IEnumerable<string> WatchMe(int record_id)
{
    GMapChatHub sendmsg = new GMapChatHub();
    sendmsg.sendHelpMessage(record_id.ToString());

    return "Done";
}

C# 代码(在 Web 项目中)

namespace GMapChat
{
    public class GMapChatHub : Hub
    {
        public void sendHelpMessage(string token)
        {
             var context = GlobalHost.ConnectionManager.GetHubContext<GMapChatHub>();
             context.Clients.All.helpMessageReceived(token, "Test help message");
        }
    }
}

Home.aspx 文件(在 Web 项目中)

var chat = $.connection.gMapChatHub;

        $(document).ready(function () {
            chat.client.helpMessageReceived = function (token,msg) {
                console.log("helpMessageReceived: " + msg);

                $('#helpMessageBody').html(msg)
                $('#helpModal').modal('toggle');
            };
          }

您不能直接调用该集线器。首先,您需要从 nuget 安装 SignalR 的 .net 客户端。然后你需要像这样初始化它:

[HttpGet]
public IEnumerable<string> WatchMe(int record_id)
{   
   using (var hubConnection = new HubConnection("your local host address")) 
   {
    IHubProxy proxy= hubConnection.CreateHubProxy("GMapChatHub");
     await hubConnection.Start();
    proxy.Invoke("sendHelpMessage",record_id.ToString());     // invoke server method
  } 
// return sth. IEnumerable<string>
}

并且每个请求都打开一个新连接可能不是一个好主意,您可以在每个会话(如果您使用)或静态或时间时创建它。