3 回答

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超3個(gè)贊
嘗試直接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貢獻(xiàn)1963條經(jīng)驗(yàn) 獲得超6個(gè)贊
這是我在 .net core 2.2 中獲取用戶 ID 的方法
首先,您需要在 Startup.cs 中注冊(cè)
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
然后為您服務(wù)
private readonly IHttpContextAccessor _httpContextAccessor;
public UserService(
IHttpContextAccessor httpContextAccessor)
{
}
var currentUserGuid = _httpContextAccessor?.HttpContext?.User?.FindFirst(UserClaimsKey.Sub)?.Value;

TA貢獻(xiàn)1883條經(jīng)驗(yàn) 獲得超3個(gè)贊
private async Task<ApplicationUser> GetUserDetailsAnsyc()
{
return await userManager.GetUserAnsync(HttpContext.User);
}
var user = await GetUserDetailsAnsyc();
Console.WriteLine(user.Id.ToString());
- 3 回答
- 0 關(guān)注
- 175 瀏覽
添加回答
舉報(bào)