【发布时间】:2023-03-19 15:12:01
【问题描述】:
用户在浏览器中提交表单后,我需要从服务器向客户端发送即时消息。
我按照微软的步骤 here 设置了一个 signalR 连接,创建了一个 Hub 类,signalr.js 等。
问题是我只能向所有客户端调用消息,但我需要将消息调用给发起请求的特定调用者(否则每个人都会收到消息)。
这是我在 HomeController.cs 中的 POST 操作:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Submit(string signalRconnectionId, Dictionary<string, string> inputs)
{
//Invoke signal to all clients sending a message to initSignal WORKS FINE
await _signalHubContext.Clients.All.SendAsync("initSignal", "This is a message from the server!");
//Invoke signal to specified client where signalRConnectionId = connection.id DOES NOT WORK
await _signalHubContext.Clients.Client(signalRconnectionId).SendAsync("initSignal", "This is a message from server to this client: " + signalRconnectionId);
return RedirectToAction("Success", inputs);
}
我的客户端 javascript 文件:
//Create connection and start it
const connection = new signalR.HubConnectionBuilder()
.withUrl("/signalHub")
.configureLogging(signalR.LogLevel.Information)
.build();
connection.start().catch(err => console.error(err.toString()));
console.log("connectionID: " + connection.id);
$("#signalRconnectionId").attr("value", connection.id);
//Signal method invoked from server
connection.on("initSignal", (message) => {
console.log("We got signal! and the message is: " + message);
});
我已尝试调试操作方法,并且正确传递了“0”的 connectionId(每个连接递增 1)
【问题讨论】:
-
在您链接的页面上,还有另一个链接解释了
Clients:docs.microsoft.com/en-us/aspnet/core/signalr/… -
Clients.Caller.SendAsync("ReceiveMessage", message);- 这将只为发起请求的客户端调用客户端函数。 -
你自己试过了吗?当我使用 _signalHubContext.Clients 时,没有可用的调用方方法。如果我从 Hub 类那里做,但是我需要把业务逻辑放在那里,我想从我通过控制器中的 DI 获得的 hubcontext 做它
-
这个假设来自:
connectionId which is "0" (incrementing by 1 per connection)
标签: c# asp.net-mvc asp.net-core asp.net-core-signalr