Asp.net-Core-Signalr

在客戶端(Angular App)上獲取 SignalrR ConnectionId

  • August 8, 2021

嗨,我正在使用 Angular 應用程序連接到信號器,我正在使用“@aspnet/signalr”:“1.0.0-preview1-final”。

我需要將 connectionId 發送到我的控制器(我需要做一些處理並告訴所有其他客戶端,但沒有使用者發出請求),問題是 Connection Id 是私有的,有辦法獲取連接 Id 嗎?

似乎是一個XY 問題

告訴所有其他客戶(問題 X)

中心:

public async Task TellAllOtherClients(object[] args)
{
   await Clients.Others.SendAsync("method", args);
}

得到connectionId(解決方案 Y)

中心:

public string GetConnectionId()
{
   return Context.ConnectionId;
}

客戶:

hub.invoke('getConnectionId')
   .then(function (connectionId) {
       // Send the connectionId to controller
   });

客戶:

let connection: signalR.HubConnection;
let accessToken = "3076a225-f2f6-4c68-b894-08accb62bb90";

connection = new signalR.HubConnectionBuilder().withUrl("http://localhost:8178/notifyHub", { accessTokenFactory: () => accessToken }).build();
connection.start().then(function(){connection.invoke("GetConnectionId").then(function(connectionId){console.log(connectionId)})}).catch(err => console.error(err));

引用自:https://stackoverflow.com/questions/50177099