当调用web-api中的特定方法时,如何调用signalr中心?

问题描述 投票:0回答:1

我刚刚开始学习signalr,我只是不明白它的结构。

说我有这个api端点。

public IActionResult Get()
{

   return Ok("You hit the endpoint!");

}

我已经实现了这样的枢纽。

public class MyHub: Hub
{
    public async Task SendMessage(string user, string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", "You called the endpoint successfully", "");

    }
}

我不明白的是,我怎样才能调用上面的端点, 当调用成功时,我可以得到一个signalr消息说 "你成功调用了端点"?

谅谅

c# asp.net-mvc asp.net-core signalr
1个回答
0
投票

假设你已经完成了连接到SignalR集线器的客户端部分代码,你只需要把集线器注入到你的控制器中,这样你就可以调用集线器的方法。注入集线器到控制器中,使用DI像。

private IHubContext<NotificationsHub, INotificationsHub> YourHub
{
    get
    {
        return this.HttpContext.RequestServices.GetRequiredService<IHubContext<YourHub, IYourHub>>();
    }
}

然后从动作中调用你的集线器方法。

public IActionResult Get()
{
    this.YourHub.Clients.All.SendAsync("ReceiveMessage", "You called the endpoint successfully");
    return Ok("You hit the endpoint!");
}
© www.soinside.com 2019 - 2024. All rights reserved.