[英]How to get SignalR IHubContext from DI in .NET Core 3.1?
[英].Net Core SignalR: Send to Users except caller from IHubContext (injected into controller)
為了僅在 controller 中使用注入的 IHubContext 時識別當前用戶,我存儲了一個具有用戶 ID 的組。 但是,我正在努力發送給其他人,因為我無法找到一種方法來找出要排除的連接 ID。
我的中心
public override Task OnConnectedAsync()
{
Groups.AddAsync(Context.ConnectionId, Context.User.Identity.Name);
return base.OnConnectedAsync();
}
在我的 controller 方法中,我可以為該用戶調用方法:
await _signalRHub.Clients.Group(User.Identity.Name).InvokeAsync("Send", User.Identity.Name + ": Message for you");
IHubContext.Clients.AllExcept 需要一個連接 ID 列表。 如何獲取已識別用戶的連接 ID,以便僅通知其他人?
正如@Pawel所建議的那樣,我現在正在對客戶端重復數據刪除,該方法可以正常工作(只要您的所有客戶端都經過身份驗證即可)。
private async Task Identification() => await Clients.Group(Context.User.Identity.Name).InvokeAsync("Identification", Context.User.Identity.Name);
public override async Task OnConnectedAsync()
{
await Groups.AddAsync(Context.ConnectionId, Context.User.Identity.Name);
await base.OnConnectedAsync();
await Identification();
}
與之配套的JS(縮寫):
var connection = new signalR.HubConnection("/theHub");
var myIdentification;
connection.on("Identification", userId => {
myIdentification = userId;
});
現在,您可以在諸如connection.on("something", callerIdentification)
方法中測試callerIdentification == myIdentification
@Tester的評論使我希望在通過IHubContext發送時在某個時候會有更好的方法。
在SignalR core中,connectionId存放在signalR連接中。 假設您有一個 signalrR 連接定義如下
signalrConnection = new HubConnectionBuilder()
.withUrl('/api/apphub')
...
.build();
每當您發出獲取請求時,請將 signalR connectionId 添加為 header。例如。
response = await fetch(url, {
...
headers: {
'x-signalr-connection': signalrConnection.connectionId,
},
});
然后在您的 controller 或任何您有權訪問 httpContextAccessor 的地方,您可以使用以下內容排除 header 中引用的連接:
public async Task NotifyUnitSubscribersExceptCaller()
{
//Grab callers connectionId
var connectionId = _httpContextAccessor.HttpContext?.Request.Headers["x-signalr-connection"] ?? "";
await _hub.Clients.GroupExcept("myGroup", connectionId).SendCoreAsync("Sample", new object[] { "Hello World!" });
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.