Home > database >  How to map a SignalR hub to a path with an argument
How to map a SignalR hub to a path with an argument

Time:09-05

I'm building a backend with Asp.Net Core & SignalR. The data are not themself located on the Asp.Net Core, but must be requested to some other devices, that will send the data to the Asp.Net Core server, and then the server must give them back to the client through the web socket.

I would like to react to the OnConnectedAsync to request my devices to send periodically some data to Asp.Net Core.

But this means that my hub must be able to know which data I need to be querying.

So I would like to have a Hub responding to the url /api/data/{id} and in my Hub, be able to know which ID has been requested.

app.MapHub<NotificationsHub>("/api/data/{id}");

The id identify a big group of data(that is requested and forwared as bulk), and multiple clients will request the same ID.

I can't find in the doc:

  • If this is possible
  • How should I specify the ID parameter?
  • How do I retrieve this ID in the hub?

If anybody has some pointer, it would be helpful, thank you very much

CodePudding user response:

You can pass parameters as query string parameters. Pass the id from the connection url:

_hubConnection = new HubConnectionBuilder()
    .WithUrl("/api/data?id=123")
    .Build();

Then read it inside hub:

public override async Task OnConnectedAsync()
{
    string id = Context.GetHttpContext().Request.Query["id"];

    var connectionId = Context.ConnectionId;
    await Groups.AddToGroupAsync(connectionId, id);

    await base.OnConnectedAsync();
}

public override async Task OnDisconnectedAsync(Exception exception)
{
    string id = Context.GetHttpContext().Request.Query["id"];

    var connectionId = Context.ConnectionId
    await Groups.RemoveFromGroupAsync(connectionId, id);
   
    await base.OnDisconnectedAsync(exception);
}

Send data:

_hubContext.Group("123").SomeMethod(dataBatch);

Map hub:

app.MapHub<NotificationsHub>("/api/data")
  • Related