如何在Web API .NET Core中获取Controller外部的当前用户

Fel*_*ana 6 asp.net-mvc asp.net-core-mvc .net-core asp.net-core asp.net-core-webapi

我正在尝试从我的Web API中的控制器之外的Context中获取当前用户.我正在使用OpenIddict对用户进行身份验证,因此授权是由令牌进行的.

我在我的Startup.cs中注册了HttpContextAcessor作为单例:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
Run Code Online (Sandbox Code Playgroud)

之后,我在我的集​​线器中注入了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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

问题是_context.User.Identity.Name始终为null.

有办法做到这一点吗?

don*_*x93 -10

尝试这个:

HttpContext.Current.User.Identity.Name
Run Code Online (Sandbox Code Playgroud)