使用SignalR 2和MVC 4.0将服务器发送到特定客户端的消息无效

imd*_*sen 6 c# asp.net-mvc-4 signalr

我想使用signalR从服务器调用通知特定客户端,但它无法正常工作.我的代码执行成功但客户端没有收到来自服务器的任何调用.

然而,这适用于所有客户.

var hubContext = GlobalHost.ConnectionManager.GetHubContext<ProcessStatusNotifyHub>();
hubContext.Clients.All.notify("Got it!");
Run Code Online (Sandbox Code Playgroud)

但这不适用于特定客户端 [更新代码] 以下代码用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);
                 }
              });
           });
       });
});
Run Code Online (Sandbox Code Playgroud)

以下代码写在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);
        }
Run Code Online (Sandbox Code Playgroud)

我已经尝试调试代码,它在.cstml或controlloer上显示客户端ID的正确值.例如clientid : 0fdf6cad-b9c1-409e-8eb7-0a57c1cfb3be

你能帮我从服务器向特定客户发送通知吗?

小智 0

这不是对您的具体问题的答案,而是对您的代码的建议。为什么不让客户端使用Signalr连接来调用服务器呢?只需在中心定义一个客户端可以调用的方法即可。然后在该方法中使用 HubCallerContext 来获取 id。

本页向您展示如何从客户端调用服务器: http://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client

然后在 hub 的方法中:

Clients.User(Context.ConnectionId).notify("Got it!");
Run Code Online (Sandbox Code Playgroud)