我正在尝试从我的Web API中的控制器之外的Context中获取当前用户。我正在使用OpenIddict对用户进行身份验证,因此授权是由令牌进行的。
我在我的Startup.cs中注册了HttpContextAcessor作为单例:
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
之后,我在我的集线器中注入了HttpContexrAcessor,如下所示:
public class NotificationHub : Hub
{
private IHttpContextAccessor _contextAccessor;
private HttpContext _context { get { return _contextAccessor.HttpContext; } }
public NotificationHub(IHttpContextAccessor contextAccessor)
{
_contextAccessor = contextAccessor;
}
public async Task JoinGroup()
{
Groups.Add(Context.ConnectionId, $"notification_{_context.User.Identity.Name}");
}
public void Send(JsonResult notification)
{
Clients.Client(Context.ConnectionId).sendNotification(notification);
}
}
问题是_context.User.Identity.Name始终为null。
有办法做到这一点吗?
试试这个:https://msdn.microsoft.com/pt-br/library/system.threading.thread.currentprincipal(v=vs.110).aspx
System.Threading.Thread.CurrentPrincipal
尝试从启动中删除此行:
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
我相信框架已经为您注册了。
我有同样的问题。对我来说,解决方案正在等待完成请求。我发布了一个命令,并没有等待结果。例如。
PostSomething() {
Task.Run(() => PostCommandAndDontWait());
}
现在我的httpContext用户没有我期望的声明。当我等待任务完成时(删除Task.Run,.Wait()。Result()等。我确实让用户接受了声明。
试试这个:
HttpContext.Current.User.Identity.Name