无法从.net核心中的HttpContext获取User.Name。 DI没有解决它

时间:2018-06-15 07:46:06

标签: .net asp.net-core asp.net-identity httpcontext

我需要将当前的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;
        //
    }
}

0 个答案:

没有答案