我正在将 SignalR 与 ASP.NET Core 2.0 一起使用,并且我正在尝试为特定用户发送通知,如下所示:
_notification.Clients.User(id).InvokeAsync("SendMes");
其中 _notification 是 IHubContext。但它不起作用。当我为所有用户发送通知时,一切正常,所有用户都会收到通知。但是当我将它发送给特定用户时,没有任何 react 。在连接中,我需要用户,但似乎他没有用户 ID。那么我该怎么做呢?通过访问身份和声明?如果是这样,如何做到这一点?
最佳答案
我遇到了类似的问题,以下文章帮助我解决了这个问题:https://docs.microsoft.com/en-us/aspnet/core/signalr/groups?view=aspnetcore-2.1
在集线器(服务器端)中,我检查了 Context.UserIdentifier 并且它为空,即使用户已通过身份验证。原来 SignalR 依赖于 ClaimTypes.NameIdentifier 而我只是在设置 ClaimTypes.Name。所以,基本上我添加了另一个声明并且它解决了(之后正确设置了 Context.UserIdentifier )。
下面,我分享我拥有的部分身份验证代码,以防万一:
var claims = userRoles.Split(',', ';').Select(p => new Claim(ClaimTypes.Role, p.Trim())).ToList();
claims.Insert(0, new Claim(ClaimTypes.Name, userName));
claims.Insert(1, new Claim(ClaimTypes.NameIdentifier, userName)); // this is the claim type that is used by SignalR
var userIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity);
小心, SignalR 用户和组区分大小写。
关于asp.net-core - SignalR 核心中的用户 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48110615/