来自控制器的 SignalR 调用 [英] SignalR call from controller

查看:27
本文介绍了来自控制器的 SignalR 调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将字符串从我的控制器传递到一个 signalR 集线器,并让它在我的页面上呈现.我遵循了以下聊天教程:https://docs.microsoft.com/en-us/aspnet/core/tutorials/signalr?view=aspnetcore-2.2&tabs=visual-studio

I'm needing to pass strings from my controller to a signalR hub and have it render on my page. I've followed along with the chat tutorial found at: https://docs.microsoft.com/en-us/aspnet/core/tutorials/signalr?view=aspnetcore-2.2&tabs=visual-studio

聊天教程的下一步是向我的控制器发出消息调用,如下所示:

The next step from the chat tutorial is breaking it out message call to my controller like so:

[HttpPost]
public async Task<IActionResult> Upload(string engineType)
{
    try
    {
        var message = "File Upload Failed";
        
        await _errorHub.Clients.All.SendAsync("SendMessage", message);
        return Ok();
    }
    catch (Exception ex)
    {
        Log.Error("File Upload failed: " + ex);
        return NotFound();
    }
}

我已将集线器注入控制器,这就是我能够访问 Clients.All... 调用的方式.

I have injected my hub into my controller, which is how I'm able to access the Clients.All... call.

我的集线器与教程的不同之处仅在于我删除了用户参数:

My hub is only different from the tutorial in that I removed the user parameter:

 public class UserErrorHub : Hub
{
    public async Task SendMessage( string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", message);
    }
}

最后,在我的 javascript 中,我设置了以下 SignalR:

Finally, in my javascript, I have the following SignalR set up:

var connection = new signalR.HubConnectionBuilder().withUrl("myURL").build();

connection.on("ReceiveMessage", function (user, message) {
    console.log("ReceiveMessage");
    var msg = message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
    var encodedMsg = user + " says " + msg;
    var li = document.createElement("li");
    li.textContent = encodedMsg;
    document.getElementById("messagesList").appendChild(li);
});

当我运行我的项目时,控制台输出通知我我的集线器设置得很好,如下所示:

When I run my project, the console output informs me that I hub is set up fine like so:

[2020-09-03T09:45:23.384Z] 信息:将/Signalr"规范化为'https://localhost:44336/Signalr'.

[2020-09-03T09:45:23.384Z] Information: Normalizing '/Signalr' to 'https://localhost:44336/Signalr'.

但是,当我触发上传方法时,没有任何内容发送到我的集线器.我做错了什么?

However, when I trigger my Upload method, nothing gets sent to my hub. What is it I'm doing wrong?

推荐答案

await _errorHub.Clients.All.SendAsync("SendMessage", message);

SendMessage" 应该是 ReceiveMessage"

这篇关于来自控制器的 SignalR 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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