Search code examples
c#signalrsignalr.client

C# SignalR client throws " 'InvokeCoreAsync' method cannot be called if the connection is not active"


My server's Program.cs contains the following lines -

builder.Services.AddSignalR();
app.MapHub<NotificationUserHub>("/NotificationUserHub");

NotificationUserHub looks like this -

public class NotificationUserHub : Hub<INotificationClient>
{
    private readonly IUsersStateContainer _container;
    public NotificationUserHub(IUsersStateContainer container) => _container = container;

    public async Task AddConnectionToGroup(string groupName)
    {
        var ctx = Context.ConnectionId;
        await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
        _container.Update(ctx, groupName);
    }

    public async Task SendNotificationToUser(Notification message)
        => await Clients.Groups(message.To).ReceiveMessage(message);
    public override async Task OnDisconnectedAsync(Exception exception)
    {
        _container.Remove(Context.ConnectionId);
        await base.OnDisconnectedAsync(exception);
    }
}

and my connection code in a Blazor client looks like this -

var url = $"{WebApiOptions.Value.BaseUrl}NotificationUserHub";
Console.WriteLine($"Hub connection should be {url}");

_hubConnection = new HubConnectionBuilder()
    .WithUrl(url)
    .WithAutomaticReconnect()
    .Build();

_hubConnection.On<Notification>("ReceiveMessage", (message) =>
{
    _notificationMessage = message.Type switch
    {
        Enums.NotificationType.NewMessage => $"New message from {message.From}",
        Enums.NotificationType.ConversationClosed => $"Conversation closed by {message.From}",
        _ => string.Empty
    };

    PageInfo.SetUnreadMessageCount(message.UnreadCount);
    if (!string.IsNullOrEmpty(_notificationMessage))
    {
        MessageNotification.Show();
    }
});

try
{
    await _hubConnection.StartAsync();
    await _hubConnection.InvokeAsync("AddConnectionToGroup", PageInfo.CurrentUserEmail);
    hubInitialised = true;
}
catch (Exception ex)
{
    Console.WriteLine(ex.ToString());
}

I get

'InvokeCoreAsync' method cannot be called if the connection is not active

at the InvokeAsync line.

The Hub method AddConnectionToGroup is never called, the Hub state says connected before the InvokeAsync and disconnected afterwards.

The obvious culprit would be the connection URL but I've checked that.


Solution

  • Turns out there was DI issue on the Hub which was preventing it from starting.

    As you were, folks.