I have BaseHub
class that is inheriting Hub
class. I overrode OnConnected and OnDisconnected methods, and they are working properly, when client and server are connected, ConnectionId
is saved inside group.
public class BaseHub : Hub
{
private readonly string _defaultGroupName = "HubUsers";
public async Task BroadcastMessage(string methodName, params object[] parameters)
{
await Clients.All.SendAsync(methodName, parameters);
}
public async Task AddUserToGroup(string groupName)
{
await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
}
public async Task RemoveUserFromGroup(string groupName)
{
await Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName);
}
public override async Task OnConnectedAsync()
{
await AddUserToGroup(_defaultGroupName);
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception exception)
{
await RemoveUserFromGroup(_defaultGroupName);
await base.OnDisconnectedAsync(exception);
}
}
When I call BroadcastMessage
, my Clients
is always null, thus I get exception.
When I tried to call await Clients.All.SendAsync(methodName, parameters);
directly inside OnConnected, Clients
object was valid and my client side method was invoked.
I even tried using protected IHubContext<BaseHub> _context;
, then I have _context
object, but 0 users insite Clients/ Groups.
BaseHub
is parent class of VotingHub
where I am calling BroadcastMessage
public async Task ShareResult(Guid result)
{
await BroadcastMessage(_receiveResult, new[] { result });
}