asp.net-mvc - 如何在 Web API .NET Core 的 Controller 之外获取当前用户

标签 asp.net-mvc asp.net-core asp.net-core-mvc .net-core asp.net-core-webapi

我正在尝试从我的 Web API 中的 Controller 外部的上下文中获取当前用户。我正在使用 OpenIddict 对用户进行身份验证,因此授权是通过 token 进行的。

我已在 Startup.cs 中将 HttpContextAcessor 注册为单例:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

之后,我在集线器中注入(inject) 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 始终为空。

有没有办法做到这一点?

最佳答案

在我使用 .Net Core 2.0 的情况下,我需要在 Controller 外部获取用户 ID,在应用程序服务中,我执行了以下操作:

启动.cs 我在 下添加了这一行配置服务

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

我创建了以下类(class)
public class UserResolverService
{
    private readonly IHttpContextAccessor _httpContext;
    private readonly UserManager<ApplicationUser> _userManager;

    public UserResolverService(IHttpContextAccessor httpContext, UserManager<ApplicationUser> userManager)
    {
        _httpContext = httpContext;
        _userManager = userManager;
    }

    public string GetUserId()
    {
        var userId = _userManager.GetUserId(_httpContext.HttpContext.User);
        return userId;
    }
}

在我的申请服务上课,我调用用户解析服务
public class MyApplicationService
{
    private readonly ApplicationDbContext _context;
    private readonly UserResolverService _userResolverService;

    public MyApplicationService(ApplicationDbContext context, UserResolverService userResolverService)
    {
        _context = context;
        _userResolverService = userResolverService;
    }

    public async Task Create(MyModel entity)
    {
        entity.CreatorUserId = _userResolverService.GetUserId();
        _context.MyModel.Add(entity);
        await _context.SaveChangesAsync();
    }
}

此外,如果您不想使用 用户管理器 ,您可以简单地制作 用户解析服务 像这样的类:
public class UserResolverService
{
    private readonly IHttpContextAccessor _httpContext;

    public UserResolverService(IHttpContextAccessor httpContext)
    {
        _httpContext = httpContext;
    }
    public string GetUserId()
    {
        var user = _httpContext?.HttpContext?.User as ClaimsPrincipal;
        var userId = user.Claims.ElementAt(0).Value;
        return userId;
    }
}

关于asp.net-mvc - 如何在 Web API .NET Core 的 Controller 之外获取当前用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41858587/

相关文章:

css - ASP.NET MVC Razor 和 css block

asp.net - 如何在 ASP.NET MVC 网站上执行定期工作?

azure - 从 .NET Core 1.1.1 升级到 .NET Core 1.1.2 后,Azure 上的 ASP.NET Core 网站无法启动并出现 502.5 错误

c# - 在 ASP.NET Core 和 EF Core 中使用 MySQL 提供程序时出现 NotImplemented 异常

c# - 创建多个表/网格

c# - 是否可以创建一个只有 Action 名称的新路线?

asp.net - 当 CustomError 设置为 "On"或 "RemoteOnly"时,运行状况监控不会记录错误

c# - 添加具有可变参数的 .Net Core 策略

npm - VS2015 CTP6 中嵌套 node_modules 的 "FullPath cannot be applied"错误

c# - 将 IHttpContextAccessor 注入(inject) ApplicationDbContext ASP.NET Core 1.0