Kénium
Kénium

Reputation: 105

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.

Upvotes: 1

Views: 836

Answers (2)

aaron
aaron

Reputation: 43073

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.

Upvotes: 1

hikalkan
hikalkan

Reputation: 2272

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.

Upvotes: 2

Related Questions