asp.net-core - SignalR 核心中的用户 ID

标签 asp.net-core asp.net-core-signalr

我正在将 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/

相关文章:

c# - 具有 ASP.NET Core 2.1 和 UWP 应用程序作为客户端的 SignalR Webhost 返回 ' 405 Method not allowed'

asp.net-core - SignalR 核心和跨域请求问题

asp.net-core - .Net Core 将表单数据发送到 uri

asp.net-core - 如何在 ASP.NET Core 中添加自定义 ValueProvider

amazon-web-services - ASP.NETCore Signalr 在 AWS 上不起作用

c# - 无法从 JavaScript 客户端连接到 ASP.NET SignalR 中心

c# - IClientProxy.SendAsync 的可能异常(来自 Microsoft.AspNetCore.SignalR)

asp.net - IIS Express 命令行 ASP.NET MVC 6 beta 8

iis - 用户配置文件和 HKLM 注册表都不可用。使用临时 key 存储库。应用程序退出时 protected 数据将不可用

javascript - SignalR - 更新特定用户(推送通知)