Search code examples
signalrsignalr-hubsignalr.clientasp.net-core-signalr

Is there a way to avoid using magic strings with the HubConnection class


I have a strongly typed Hub on the server:

public Foo : Hub<Bar> {}

Bar is supposed to be an interface including methods available on the client side. But that solves only half of the problem (the server half). On the client side, I still have to use magic strings to define handlers for calls to the methods of Bar:

 hubConnection.On<int>("MethodInsideBar", param => DoSomething(param));

Is there a way to avoid doing this ? Shouldn't there be a way to implement Bar client side and link the calls from the server to that implementation ?


Solution

  • On the client side, I still have to use magic strings to define handlers for calls to the methods of Bar:

    hubConnection.On<int>("MethosInsideBar", param => DoSomething(param)); 
    

    Is there a way to avoid doing this ? Shouldn't there be a way to implement Bar client side and link the calls from the server to that implementation ?

    As far as I know, the Strongly typed hubs only apply to the server side, we could inject the strongly-typed HubContext in the controller, then, call the hub method. It can prevent the method name is misspelled or missing from the client.

    On the client side, we still need to use the Invoke method call the public methods on hubs, and define a method using the on method of the HubConnection to receive messages from the hub.

    When calling the public hub methods from client, if you want to use the Strongly typed Hubs, you could inject the Strongly typed hubcontext into the controller, then use JQuery Ajax call the controller's action method, then use the Strongly typed hubs method. Refer this thread: SignalR - Call statically typed hub from Context.