SignalR: How to truly call a hub's method from the server / C#

前端 未结 2 889
囚心锁ツ
囚心锁ツ 2021-02-07 04:17

I\'m trying to improve my application which will require calling a hub from C# instead of javascript. The current workflow for adding a task in my app is:

  • make an
2条回答
  •  别那么骄傲
    2021-02-07 04:51

    In order to truly call a hub method, as you call it, you have to be connected to it, and call over that connection. By calling something different (your API) you cannot do that kind of call, and therefore you have to resort to the server initiated broadcasting capabilities, which by nature cannot know about what the Caller is because there's no SignalR's caller.

    That said, if your client calling the API (no matter if it's Javascript or C#) is already connected to the hub when performing the call, you can always decorate your call towards the API with the connectionId of your hub's connection (by query string, by headers, ...). If your API receives that information, it can then simulate the Caller API with

    Clients.Client(connectionId)
    

    and it can do the same for Others with

    Clients.AllExcept(connectionId)
    

    over a IHubContext instance. Check the official docs.

    You can then follow the suggestion from DDan about encapsulating the IHubContext usage in a convenient centralized way, or even restructure it a bit to make it easily DI-compliant.

提交回复
热议问题