Sending a message from the server to a specific client does not work using SignalR 2 and MVC 4.0

I wanted to trigger a notification of a specific client from the server using signalR, but it did not work. my code was successfully executed, but the client dose did not receive any call from the server.

However, this works for the entire client.

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

But this does not work for a specific client [Updated code] The following code written in 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); } }); }); }); }); 

The following code is written in 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); } 

I tried debugging code showing the correct client id value on .cstml or controller. e.g. clientid : 0fdf6cad-b9c1-409e-8eb7-0a57c1cfb3be

Could you help me send a notification to a specific client from the server.

+5
source share
2 answers

The hubContext.Clients.User(string) operation expects the user ID of the current HTTP request, not the SignalR client ID.

If you want to use the client identifier, use this operation:

 hubContext.Clients.Client( ) 

If you want to access it from the current user, you can get the current user ID using this

 string UserID=User.Identity.GetUserId() 
+1
source

This is not an answer to your specific question, but instead a suggestion about your code. Why not use the Signalr client connection to invoke the server? Just define a method in the hub that the client can call. Then in this method use the HubCallerContext to get the identifier.

This page shows how to call the server from the client: http://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client

Then in the hub method:

 Clients.User(Context.ConnectionId).notify("Got it!"); 
0
source

Source: https://habr.com/ru/post/1210092/


All Articles