简体   繁体   中英

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.

I think that the problem can be related to property injection you are using:

public IAbpSession AbpSession { get; set; }

While SignalR uses DI, it does not create Chat class from DI container. That means property injection does not work. But constructor injection would work since it passes ctor parameters from DI container.

So, use constructor injection instead of property injection.

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM