Search code examples
c#authenticationasp.net-coresignalraspnetboilerplate

Get the UserId from AbpSession in SignalR Hub


I can't get the UserId from AbpSession inside a class that implements ITransientDependency.

public class Chat : Hub, ITransientDependency
{
    public IAbpSession AbpSession { get; set; }

    public ILogger Logger { get; set; }

    public Chat()
    {
        AbpSession = NullAbpSession.Instance;
        Logger = NullLogger.Instance;
    }

    private static List<MemberDto> _members = new List<MemberDto>();

    public Task Send(string message)
    {
        return Clients.All.InvokeAsync("Send", string.Format("User {0}: {1}", UserId(), message));
    }

    public long? UserId()
    {
        return AbpSession.UserId;
    }
}

Properties UserId and TenantId are still null.

Chat class is inside the "Application" layer where AbpSession is working well.


Solution

  • This works with SignalR AspNetCore Integration. I tried here:

    public async Task SendMessage(string message)
    {
        await Clients.All.InvokeAsync("getMessage", string.Format("User {0}: {1}", AbpSession.UserId, message));
    }
    

    You can now download v3.4.1 of the template with the Abp.AspNetCore.SignalR preview.

    Update

    You're probably not passing in the encryptedAuthToken as done in SignalRAspNetCoreHelper.ts:

    var encryptedAuthToken = new UtilsService().getCookieValue(AppConsts.authorization.encrptedAuthTokenName);
    var qs = AppConsts.authorization.encrptedAuthTokenName + "=" + encodeURIComponent(encryptedAuthToken);
    

    Then pass it as a query string in the URL of your SignalR hub.