在Web API调用上检索SignalR connectionId

问题描述 投票:2回答:1

我有以下星座:

我正在使用一个asp.net核心web api项目,该项目还包括一个HubContext。用户要做的第一件事就是对我的UsersController : BaseController进行api调用。在这里他/她称api/login路线通过相应的凭据。 Login()函数的返回值是JwtBearerToken,用户从那时起用于所有其他api调用。

一旦发出令牌,用户(客户端)就会通过我的ConnectionHub : Hub建立SignalR连接。

到目前为止一切运行良好,用户在调用api方法时使用令牌进行身份验证,我也可以在ConnectionHub范围内跟踪相应的会话状态。

现在,每当他/她进行api调用时,我都必须检索用户(SignalR)会话ID。

一世。即当用户在我的UsersController中调用一个方法时,我想做这样的事情:


[HttpGet]
public ActionResult<List<User>> GetAll()
{
    // Here I want to retrieve the (SignalR) session id of the user calling this method.
    return Ok( userRepository.GetAllUsers() );
}

到目前为止,我唯一的想法是让用户使用相应的api调用发送他的SignalR-SessionId,但我想要实现的是在服务器端读取Id。我怎样才能做到这一点?

c# asp.net-core asp.net-core-webapi asp.net-core-signalr
1个回答
0
投票

根据Microsoft documentation,无法将用户的connectionId置于集线器之外(例如在控制器中):

从Hub类外部调用hub方法时,没有与调用关联的调用方。因此,无法访问ConnectionIdCallerOthers属性。


但是,您可以通过调用hub方法来获取JavaScript用户。在这里,您可以使用您的存储库访问connectionId和数据库(确保它可以通过依赖注入获得)。

我不知道你想对用户做什么,但你可以简单地返回hub方法中的用户并使用connectionId做一些事情。

YourHubClass.cs

public Task GetAllUsers()
{
    // Get the ConnectionId
    var connectionId = Context.ConnectionId;

    // Get the users list
    var users = userRepository.GetAllUsers(); 

    // ...

    return Clients.User(user).SendAsync("UserListRequested", users);
}
© www.soinside.com 2019 - 2024. All rights reserved.