【问题标题】:How to invoker a signalr hub when calling a specific method in a web-api?在 web-api 中调用特定方法时如何调用信号器集线器?
【发布时间】:2020-05-13 17:53:48
【问题描述】:

我刚开始学习 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", "");

    }
}

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

谢谢

【问题讨论】:

  • 您在使用 .Net Core 应用程序吗?
  • 您可以参考this

标签: c# asp.net-mvc asp.net-core signalr


【解决方案1】:

假设您已经完成了连接到 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!");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-18
    • 1970-01-01
    相关资源
    最近更新 更多