简体   繁体   中英

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:

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. 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. What can I change to be able to invoke the hub method successfully?

You'd have to pass your ConnectionId as a parameter, and you can't get that until SignalR is already connected.

SignalR connections are only present for one "page view" on the client. 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 . Because of that, base.Context.ConnectionId essentially doesn't exist when you're trying to use it here.

That leaves you with two options.

  1. Subscribe to updates after SignalR connects on each page. 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) . This is a standard approach in 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. 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 . If that's called with AJAX, you could just append the ConnectionId as a query parameter and all of this would be moot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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