Big Daddy
Big Daddy

Reputation: 5234

Call SignalR Hub From Another .Net Project

I've got SignalR hubs in one .NetCore project and SignalR clients in another .NetCore project (to comply with internal infrastructure guidelines). I'm struggling with how to implement the client code that will provide the connection to the hubs. All my projects build fine, I'm just missing the connectivity part.

Client Project:

public class MyClientController
    {
        private readonly IHubContext<MyHub, IMyHubClient> _hub;

        public MyClientController(IHubContext<MyHub, IMyHubClient> hub)
        {
            _hub = hub;
            // THIS NEVER GETS CALLED/HIT BECAUSE I DON'T KNOW HOW TO REGISTER IT
            _hub.Clients.All.BroadcastMessage("Notify", $"Hello everyone.  This has been constructed");
        }
}

I'm guessing I need to do some configuration in the Startup.Configure() method? I've installed the client package already,

EDIT: I added the following code, but it's complaining about the format (remember, this is not a relative path, it's in another service).

app.UseEndpoints(endpoints =>
{
     endpoints.MapHub<MyHub>("http://localhost:60913/myHub");
}

Am I on the right path here?

Upvotes: 1

Views: 1425

Answers (1)

Noah Stahl
Noah Stahl

Reputation: 7623

The connection is made by mapping a route to your hub class. The docs have a good example. This includes:

// Add to services collection
services.AddSignalR();
// Map the route "/chathub" to a ChatHub class
app.UseRouting();
app.UseEndpoints(endpoints =>
{
    endpoints.MapHub<ChatHub>("/chathub");
});

By the way, a hub can be a standalone class not associated to a controller.

Upvotes: 1

Related Questions