How to use SignalR hub instance outside of the hubpipleline

百般思念 提交于 2019-11-26 15:36:22

问题


I am using SignalR to broadcast messages to all my clients. I need to trigger the broadcasting outside of my hub class i.e. something like below:

var broadcast = new chatHub(); broadcast.Send("Admin","stop the chat");

I am getting error message as:

Using a Hub instance not created by the HubPipeline is unsupported.


回答1:


You need to use GetHubContext:

var context = GlobalHost.ConnectionManager.GetHubContext<chatHub>();
context.Clients.All.Send("Admin", "stop the chat");

This is described in more detail at http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-server#callfromoutsidehub.




回答2:


A small update for those who might be wondering where the GlobalHost has gone. SignalR has been completely rewritten for .net core. So if you are using the SignalR.Core package (Difference between SignalR versions), you get an instance of SignalR hub context by injecting it into your service:

public class MyNeedyService
{
    private readonly IHubContext<MyHub> ctx;

    public MyNeedyService(IHubContext<MyHub> ctx)
    {
        this.ctx = ctx;
    }

    public async Task MyMethod()
    {
        await this.ctx.All.SendAsync("clientCall");
    }
}

And in Startup.cs:

services.AddSignalR()/*.AddAzureSignalR("...")*/;

Microsoft docu is here: Send SignalR messages from outside the hub.



来源:https://stackoverflow.com/questions/15128125/how-to-use-signalr-hub-instance-outside-of-the-hubpipleline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!