Hi @mc ,
You can get the user id via the following code:
var userId = Context.UserIdentifier;
Or find the user via DbContext and the username, code like this:
var user = _dbContext.Users.Where(c => c.UserName == username).FirstOrDefault();
if(user != null)
{
var id = user.Id;
}
The detail sample code as below: (In my sample, the user id is a Guid value, and it is auto generated when insert new user)
[Authorize]
public class MyChatHub : Hub
{
private static Dictionary<string, List<string>> NtoIdMappingTable = new Dictionary<string, List<string>>();
private readonly ApplicationDbContext _dbContext;
public MyChatHub(ApplicationDbContext applicationDbContext)
{
_dbContext = applicationDbContext;
}
public override async Task OnConnectedAsync()
{
var username = Context.User.Identity.Name;
var userId = Context.UserIdentifier;
var user = _dbContext.Users.Where(c => c.UserName == username).FirstOrDefault();
if(user != null)
{
var id = user.Id;
}
List<string> userIds;
//store the userid to the list.
if (!NtoIdMappingTable.TryGetValue(username, out userIds))
{
userIds = new List<string>();
userIds.Add(userId);
NtoIdMappingTable.Add(username, userIds);
}
else
{
userIds.Add(userId);
}
await base.OnConnectedAsync();
}
The debug screenshot:
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion