How to extend the class to add a property UserId?

mc 1,921 Reputation points
2021-09-23T01:28:12.25+00:00

I am using Signalr and there is a class:

public class Device:Hub<T>
{

}

I want to add a property UserId in the class. so I want to ask how to add a property to the class Hub so I can use it?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
3,140 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
1,479 questions
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 24,236 Reputation points Microsoft Vendor
    2021-09-23T07:48:09.42+00:00

    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:

    134518-2.gif


    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

    0 comments No comments

0 additional answers

Sort by: Most helpful