从集线器向信号发送 Signalr 消息无效

Sending Signalr message from hub to signal has no effect

我有一个 asp.net 网络核心应用程序,我想在其中从集线器向客户端发送消息(相反的过程已经为我工作)。

所以我有这个控制器操作,我将我的集线器注入到:

    public IActionResult to()
    {
        _hub.Clients.All.SendAsync("ReceiveMessage", "user", "message");
        return View("~/Views/msg/ClientReceiver.cshtml");
    }

所以,它基本上只是发送一条消息,然后返回一个视图。

视图如下:

<!DOCTYPE html>
<html>
<body>

    <button onclick="receive()">Receive msg from server</button>


    <script src="~/lib/signalr/signalr.js"></script>
    <script src="~/js/ClientReceiver.js"></script>
</body>
</html> 

被引用的``ClientReceiver.js`文件如下所示:

function receive() {
    const connection = new signalR.HubConnectionBuilder()
        .withUrl("/NotificationHub")
        .configureLogging(signalR.LogLevel.Information)
        .build();


    connection.on("ReceiveMessage", (user, message) => {
        alert(message);
    });
}

查看 the documentation(转到标题“从集线器调用客户端方法”)时,这似乎应该可行。

虽然这不起作用,但没有出现警报消息。 我浏览器中的控制台指示已建立正确的连接:

[2021-06-24T23:11:48.359Z] Information: Normalizing '/NotificationHub' to 'https://localhost:44385/NotificationHub'. 

当你进入return的to方法到你的ClientReceiver.cshtml页面时,你的ClientReceiver还没有连接,所以页面收不到你的消息,你应该重写一个方法, 每次点击按钮发送消息都要访问该方法

您可以尝试像下面这样更改您的 ClientReceiver.js

function receive() {
$.ajax({
    url: '/home/send',
    type: 'get',
});
}

var connection = new signalR.HubConnectionBuilder()
    .withUrl("/NotificationHub")
    .build();
connection.on("ReceiveMessage", function (user,message) {
    alert(message);
});
connection.start();

控制器:

    private readonly IHubContext<NotificationHub> _hub;

    public HomeController( IHubContext<NotificationHub> hub)
    {
        _hub = hub;
    }

    public IActionResult To()
    {
        return View("~/Views/msg/ClientReceiver.cshtml");
    }
     public async Task SendAsync()
    {
        await _hub.Clients.All.SendAsync("ReceiveMessage", "user", "message");
    }

测试结果: