gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 16:14:55 30 4
gpt4 key购买 nike

我正在尝试从我的 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com