[英]Ignoring a client when broadcasting a message with SignalR
I want to ignore the client that made the request to broadcast the message my web app. 我想忽略发出请求广播我的Web应用程序消息的客户端。 The only way I can seem to do this is by caching the connectionId of the current user: 我似乎可以做到这一点的唯一方法是缓存当前用户的connectionId:
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? 有没有更好的方法可以忽略发出请求的客户端?
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>
编辑:根据评论中的讨论,使用GlobalHost.ConnectionManager.GetHubContext<T>
时Others
不可用
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
. 您将需要继续使用当前方法,或者找到一种方法将此活动委托给BroadcastHub
来访问“ Others
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.