簡體   English   中英

SignalR 如何訪問已連接用戶的聲明?

[英]SignalR how can I get access to claims from connected users?

在我的應用程序 .net 核心中,我想通知用戶其他用戶所做的一些操作。 我的 SignalR 連接已獲得授權,因此 SignalR 應該有權訪問已連接的用戶聲明,他擁有。 在此處輸入圖像描述

在這些聲明中,用戶有 ID,所以我想也許我可以根據該 ID 以某種方式搜索用戶,並將通知發送給特定用戶,但我不知道如何在 mHubContext 中找到他,或者我應該以其他方式做嗎?

也許我應該重寫OnConnected方法並將他們的 Id 存儲在一些 static 哈希集/字典中?

您可以使用以下方法來訪問一些屬性用戶、連接等。

[HubName("demoHub")]
public class DemoHub : Hub
{
    public readonly static ConnectionMapping<string> connections = 
        new ConnectionMapping<string>();

    public override async Task OnConnected()
    {
        string name = Context.User.Identity.Name;
        connections.Add(name, Context.ConnectionId);
        //await Groups.Add(Context.ConnectionId, Context.QueryString["group"]);
        await base.OnConnected();
    }

    public override async Task OnDisconnected(bool stopCalled)
    {
        string name = Context.User.Identity.Name;
        connections.Remove(name, Context.ConnectionId);
        //await Groups.Remove(Context.ConnectionId, Context.QueryString["group"]);
        await base.OnDisconnected(stopCalled);
    }

    public override async Task OnReconnected()
    {
        string name = Context.User.Identity.Name;
        if (!connections.GetConnections(name).Contains(Context.ConnectionId))
        {
            connections.Add(name, Context.ConnectionId);
            //await Groups.Add(Context.ConnectionId, Context.QueryString["group"]);
        }
        await base.OnReconnected();
    }
}

更新:如果需要,您可以使用以下方法或使用相同的邏輯創建類似的方法:

public Task JoinToGroup(string groupName)
{
    return Groups.Add(Context.ConnectionId, groupName);
}

public Task LeaveFromGroup(string groupName)
{
    return Groups.Remove(Context.ConnectionId, groupName);
}

public async Task AddToGroup(string connectionId, string groupName)
{
    await Groups.Add(connectionId, groupName);
    //await Clients.Group(groupName).ReceiveMessage("Send", $"{Context.ConnectionId} has joined the group {groupName}.");
}

public async Task RemoveFromGroup(string connectionId, string groupName)
{
    await Groups.Remove(connectionId, groupName);
    //await Clients.Group(groupName).ReceiveMessage("Send", $"{Context.ConnectionId} has left the group {groupName}.");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM