我需要将当前的ApplicationUser信息添加到我的上下文中(继承自IdentityDbContext。为此,我创建了一个UserResolverService,如Rion Williams所述。我已经注册了IHttpContextAccessor
和{{1在启动中。但即使在服务中,用户仍然为空,即使用户是积极登录的。我缺少什么?
我创建了一个看起来像这样的简单环境:
ApplicationDbContext:
UserResolverServices
我的UserResolverService
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
private string _userName;
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, UserResolverService userService)
: base(options)
{
_userName = userService.GetActualUser();
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
}
我的ConfigureServices:
public class UserResolverService
{
private readonly IHttpContextAccessor _accessor;
public UserResolverService(IHttpContextAccessor accessor)
{
_accessor = accessor;
}
public string GetActualUser()
{
if(_accessor.HttpContext.User.Identity.IsAuthenticated == true)
{
return _accessor.HttpContext.User?.Identity?.Name;
}
var dummy = "Dummy";
return dummy;
//
}
}