我想使用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正确值的代码。例如
clientid : 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/