Ignoring a client when broadcasting a message with SignalR

随声附和 提交于 2019-12-12 10:10:38

问题


I want to ignore the client that made the request to broadcast the message my web app. The only way I can seem to do this is by caching the connectionId of the current user:

public class BroadcastHub : Hub
{

    public override Task OnConnected()
    {
        System.Runtime.Caching.MemoryCache.Default.Set(HttpContext.Current.User.Identity.Name + "-connectionId", Context.ConnectionId, new CacheItemPolicy() { Priority = CacheItemPriority.Default, SlidingExpiration = TimeSpan.FromHours(1), AbsoluteExpiration = MemoryCache.InfiniteAbsoluteExpiration });

        return base.OnConnected();
    }

    public override Task OnReconnected()
    {
        System.Runtime.Caching.MemoryCache.Default.Set(HttpContext.Current.User.Identity.Name + "-connectionId", Context.ConnectionId, new CacheItemPolicy() { Priority = CacheItemPriority.Default, SlidingExpiration = TimeSpan.FromHours(1), AbsoluteExpiration = MemoryCache.InfiniteAbsoluteExpiration });

        return base.OnReconnected();
    }

}

This allows me to do the following in the controller action method:

        IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<BroadcastHub>();
        hubContext.Clients.AllExcept((string)MemoryCache.Default.Get(HttpContext.Current.User.Identity.Name + "-connectionId")).sendAddedPasswordDetail(addedPassword);

This method seems to work... but I'm thinking it might be the wrong way of doing things. Is there a better way to ignore the requesting client?


回答1:


There is a specific property that allows this particular exception,

hubContext.Clients.Others.YourMethodHere

You can see it used here.

Edit: As per the discussion in the comments, Others is not available when using GlobalHost.ConnectionManager.GetHubContext<T>

You will either need to continue using your current method or find a way to delegate this activity to the BroadcastHub to have access to Others.



来源:https://stackoverflow.com/questions/26104344/ignoring-a-client-when-broadcasting-a-message-with-signalr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!