简体   繁体   English

从MVC控制器添加SignalR集线器组

[英]Adding a SignalR Hub Group from an MVC Controller

I have a SignalR Hub with a non-static method that adds creates a new group based on the email address entered in a form: 我有一个带有非静态方法的SignalR集线器,该方法会根据在表格中输入的电子邮件地址添加一个新组:

public class EmailHub : Hub
{
    public void AddEmail(string email)
    {
        base.Groups.Add(base.Context.ConnectionId, email);
    }
}

I would like to call this Hub method from my MVC controller. 我想从我的MVC控制器调用此Hub方法。 My method currently looks something like this: 我的方法目前看起来像这样:

public class MyController : Controller
{
    public ActionResult AddEmail(string email)
    {
        var hub = GlobalHost.ConnectionManager.GetHubContext<EmailHub>();
        hub.Clients.All.AddEmail(email);

        return View();
    }
}

However, the code in the controller does not call the hub method. 但是,控制器中的代码不会调用hub方法。 What can I change to be able to invoke the hub method successfully? 我可以更改什么才能成功调用hub方法?

You'd have to pass your ConnectionId as a parameter, and you can't get that until SignalR is already connected. 您必须将ConnectionId作为参数传递,直到SignalR已连接,您才能获得它。

SignalR connections are only present for one "page view" on the client. SignalR连接仅在客户端上存在一个“页面视图”。 In other words, if I go to /chat/rooms/1 , I get a ConnectionId , then if I navigate to /chat/rooms/2 , I get a different ConnectionId . 换句话说,如果我去/chat/rooms/1 ,我得到一个ConnectionId ,然后,如果我导航到/chat/rooms/2 ,我得到一个不同的 ConnectionId Because of that, base.Context.ConnectionId essentially doesn't exist when you're trying to use it here. 因此,当您尝试在此处使用base.Context.ConnectionId时, base.Context.ConnectionId根本不存在。

That leaves you with two options. 剩下两个选择。

  1. Subscribe to updates after SignalR connects on each page. 在每个页面上连接SignalR之后,订阅更新。 In this scenario, you'd file a typical AddEmail request, then in JavaScript after that View() loads, you load SignalR, connect, then file a hub.server.addEmail(email) . 在这种情况下,您将提交一个典型的AddEmail请求,然后在加载View()之后在JavaScript中加载,加载SignalR,进行连接,然后提交hub.server.addEmail(email) This is a standard approach in SignalR. 这是SignalR中的标准方法。

  2. This is essentially the same thing, but if you were using an SPA framework that lets you persist your SignalR connection between views, that would work. 这本质上是同一件事,但是如果您使用的是SPA框架,该框架可让您在视图之间持久化SignalR连接,那将起作用。 Of course, that's a pretty significant change. 当然,这是一个非常重大的变化。

I've based all of this on the assumption that your action AddEmail is actually a page, which I inferred from that it returns a ViewResult . 我基于所有这些假设,假设您的操作AddEmail实际上是一个页面,据此推断它返回一个ViewResult If that's called with AJAX, you could just append the ConnectionId as a query parameter and all of this would be moot. 如果使用AJAX进行调用,则可以将ConnectionId附加为查询参数,而所有这些都没有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM