Search code examples
javascriptasp.net-mvc-3signalrsignalr-hubsignalr.client

Not able to call client method on OnDisconnected


I've a disconnect method in TestHub(which is inherited by Hub) class for signal R. I'm not able to call javascript method fnDeleteCustomer from OnDisconnected method, however same same js method gets called on Connect method. What I'm doing wrong?

 public override Task OnDisconnected()
        {
            try
            {
                 var customer = ConnectedUsers.Find(x => x.ConnectionID == Context.ConnectionId);
                if (customer!=null)
                {
                  Clients.Client(customer.ConnectionID).fnDeleteCustomer(customer.UserId);
                  return base.OnDisconnected();
                }
            }
            catch { };
            return null;
        }

Solution

  • According to MSDN:

    Occurs when a connection disconnects from this hub instance.

    So you have no any alive connection and you cannot access the client hub and its methods.

    I suppose you should use client-side disconnected event:

    $.connection.hub.disconnected(function() {
        $.connection.hub.fnDeleteCustomer(userId);
    });
    

    More information about signalr lifetime events can be found here.