简体   繁体   中英

Access SignalR Hub Context.Items from an singleton service in ASP.NET Core

I am attempting to paginate my signalR broadcast of a large table so that each subscribed group has a "current page" that the users see. I want the state of the page number to live in the Hub's Context.Items dictionary.

In my hub I set page number like this:

public class OnlineBotsHub : Hub
{
    public async Task JoinGroup(string num)
    {
        await Groups.AddToGroupAsync(Context.ConnectionId, num);
        await Clients.Group(num).SendAsync("AddedToGroup", "added to group number: " + num);
    }

    public void Pagination(string pageNum)
    {
        Context.Items.Add("page", pageNum);
    }
}

Currently I inject my hub into the singleton service like this:

private readonly IHubContext<OnlineBotsHub> _hub;
public OnlineBotService(IHubContext<OnlineBotsHub> hub)
{
    _hub = hub;
}

But I cannot seem to access the Hub's Context.Items property with this reference. I would like to use this value in a singleton service like this:

Context.Items.TryGetValue("page", out object currentPage);
var returnList = PagedList<T>.ToPagedList(addBots.OrderBy(x => x.RowId), currentPage, 100);

Am I able to access the Hub's Context.Items dictionary from this other class somehow?

Am I able to access the Hub's Context.Items dictionary from this other class somehow?

No.

You should instead have a service that holds group information that both your Hub and your OnlineBotService can access and use.

I cannot seem to access the Hub's Context.Items property with this reference

Context.Items.TryGetValue("page", out object currentPage);

It seems that you are accessing to HttpContext.Items , not HubCallerContext.Items you set in hub method.

And please note that HubCallerContext is a context abstraction for accessing information about the hub caller connection, there's no caller associated with the invocation in your custom/singleton service that is outside of your Hub class, therefore you cannot get data via HubCallerContext.Items property from outside of the Hub class.

If possible, you can try to save data in some cache store in your hub method, then you can get stored from cache store in your singleton service.

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