3 回答
TA贡献1804条经验 获得超3个赞
尝试直接IHttpContextAccessor 注入ApplicationDbContext:
public class ApplicationDbContext : IdentityDbContext<AppUser>
{
private readonly IHttpContextAccessor _httpContextAccessor;
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IHttpContextAccessor httpContextAccessor)
: base(options)
{
_httpContextAccessor= httpContextAccessor;
}
//other methods
private void CheckBeforeSaving()
{
var userId = _httpContextAccessor?.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
//...
}
}
TA贡献1963条经验 获得超6个赞
这是我在 .net core 2.2 中获取用户 ID 的方法
首先,您需要在 Startup.cs 中注册
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
然后为您服务
private readonly IHttpContextAccessor _httpContextAccessor;
public UserService(
IHttpContextAccessor httpContextAccessor)
{
}
var currentUserGuid = _httpContextAccessor?.HttpContext?.User?.FindFirst(UserClaimsKey.Sub)?.Value;
TA贡献1883条经验 获得超3个赞
private async Task<ApplicationUser> GetUserDetailsAnsyc()
{
return await userManager.GetUserAnsync(HttpContext.User);
}
var user = await GetUserDetailsAnsyc();
Console.WriteLine(user.Id.ToString());
- 3 回答
- 0 关注
- 105 浏览
添加回答
举报