【问题标题】:Sending Signalr message from hub to signal has no effect从集线器向信号发送 Signalr 消息无效
【发布时间】:2021-06-25 10:49:31
【问题描述】:

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

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

    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'. 

【问题讨论】:

    标签: asp.net asp.net-core signalr


    【解决方案1】:

    当你输入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");
        }
    

    测试结果:

    【讨论】:

    • 这很有意义。但是关于控制器中的sendAsync() 函数。我不太清楚每次按下按钮时都会调用它吗?你是怎么做到的?
    猜你喜欢
    • 2017-04-24
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-16
    • 1970-01-01
    相关资源
    最近更新 更多