I have the following constellation:
I am using a asp.net core web api project which also includes a HubContext. The first thing a user has to do is to make an api call to my UsersController : BaseController
. Here he/she calls the api/login
route passing the according credentials. The return value of the Login()
function is a JwtBearerToken, which the user from then on uses for all other api calls.
Once the token has been issued, the user (Client) establishes a SignalR connection over my ConnectionHub : Hub
.
So far everything works well, the user gets authenticated using the token when calling api methods and I also can track the according Session state inside the scope of my ConnectionHub
.
Now I have to retrieve the users (SignalR) session id whenever he/she makes an api call.
ie When the user calls a method in my UsersController
I want to do something like this:
[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() );
}
So far the only idea I have is to make the user send his SignalR-SessionId with the according api call, but what I'd like to achieve is to read the Id on the server side. How can I achieve this?
According to the Microsoft documentation , it is not possible to get the user's connectionId
outside the hub (eg in a controller):
When hub methods are called from outside of the Hub class, there's no caller associated with the invocation. Therefore, there's no access to the
ConnectionId
,Caller
, andOthers
properties.
However, you can get the users with JavaScript by calling a hub method. Here you have access to the connectionId
and to the database using your repository (make sure it is available via Dependency Injection).
I don't know what you want to do with the user's exactly, but you can simply return the users in the hub method and do something with the 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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.