用户在浏览器中提交表单后,我需要从服务器向客户端发送即时消息。
我按照Microsoft的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)
最佳答案
所以这是我从this thread的答案中得到的最终解决方案
我通过从客户端调用Hub类,然后从客户端调用传入connectionId的 Controller 来获取connectionId。
轮毂类:
public class SignalHub : Hub
{
public string GetConnectionId()
{
return Context.ConnectionId;
}
}
启动时执行的客户端javascript代码:
connection.start().catch(err => console.error(err.toString())).then(function(){
connection.invoke('getConnectionId')
.then(function (connectionId) {
// Send the connectionId to controller
console.log("connectionID: " + connectionId);
$("#signalRconnectionId").attr("value", connectionId);
});
});
HomeController.cs:
public async Task<IActionResult> Submit(string signalRconnectionId, Dictionary<string, string> inputs)
{
//Invoke signal to specified client WORKS NOW
await _signalHubContext.Clients.Client(signalRconnectionId).SendAsync("initSignal", "This is a message from server to this client: " + signalRconnectionId);
return RedirectToAction("Success", inputs);
}
它可以正常工作,但仍然有点像往返,如果我们不必通过集线器类来实现此目的,那会更容易。可能只是从客户端开始具有connectionId,但也许有充分的理由进行设计:)
关于c# - 从 Controller ASP.NET Core 2.1到特定客户端的SignalR调用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51821081/