我想使用 signalR 从服务器调用通知特定客户端,但它不起作用。我的代码已成功执行,但客户端没有收到来自服务器的任何调用。
但是这适用于所有客户端。
var hubContext = GlobalHost.ConnectionManager.GetHubContext<ProcessStatusNotifyHub>();
hubContext.Clients.All.notify("Got it!");
但这不适用于特定的客户端 [更新代码] 以下代码用 chat.cshtml 编写
$(function () {
// Reference the auto-generated proxy for the hub.
var chat = $.connection.processStatusNotifyHub;//chatHub;
chat.client.notify = function (msg) {
alert(msg);
}
// Start the connection.
$.connection.hub.start().done(function () {
var myClientId = $.connection.hub.id;
console.log('connected: ' + myClientId);
$('#sendmessageToClient').click(function () {
//chat.server.send('imdadhusen', 'This is test text');
$.ajax({
url: '@Url.Action("Send", "PushNotification")',
type: 'POST',
data: { 'clientID': myClientId },
dataType: 'json',
success: function (result) {
alert(result.status);
}
});
});
});
});
以下代码是在Controller中编写的
[HttpPost]
public ActionResult Send(string clientID)
{
var hubContext = GlobalHost.ConnectionManager.GetHubContext<ProcessStatusNotifyHub>();
//hubContext.Clients.All.notify("Got it!");
hubContext.Clients.User(clientID).notify("Got it!");
responseResult result = new responseResult();
result.status = "OK";
result.message = "Notification sent successfully";
return Json(result, JsonRequestBehavior.AllowGet);
}
我已经尝试调试它在 .cstml 或 controlloer 上显示正确的客户端 ID 值的代码。例如客户端编号:0fdf6cad-b9c1-409e-8eb7-0a57c1cfb3be
能否请您帮我从服务器向特定客户端发送通知。
最佳答案
hubContext.Clients.User(string)
操作需要当前 HTTP 请求的用户 ID,而不是 SignalR 的客户端 ID。
如果您想使用客户端 ID,请使用此操作:
hubContext.Clients.Client( )
如果你想通过当前用户访问它,那么你可以用这个获取当前用户ID
string UserID=User.Identity.GetUserId()
关于c# - 使用 SignalR 2 和 MVC 4.0 从服务器向特定客户端发送消息不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27702547/