[英]Sending message from server to specific client is not working using SignalR 2 and MVC 4.0
我想使用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()
這不是您的具體問題的答案,而是對您的代碼的建議。 為什么不讓客戶端使用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!");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.