【问题标题】:Identity AuthenticationManager with unity.mvc带有 unity.mvc 的 Identity AuthenticationManager
【发布时间】:2020-09-28 06:04:40
【问题描述】:

我正在对使用身份登录的现有 asp.net MVC 网站实施依赖注入。

User.Identity.IsAuthenticated 始终为假

我安装了 NuGet 包:Install-Package Unity.Mvc

在 Unity.Config 中添加以下代码

container.RegisterType<ApplicationDbContext>(new HierarchicalLifetimeManager());
                container.RegisterType<UserManager<ApplicationUser>>(new HierarchicalLifetimeManager());
                container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(new HierarchicalLifetimeManager());
    
                var accountInjectionConstructor = new InjectionConstructor(new ApplicationDbContext());
                container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(accountInjectionConstructor);
    
                container.RegisterType<IAuthenticationManager>(new InjectionFactory(o => HttpContext.Current.GetOwinContext().Authentication));

AccountController 构造函数

private readonly UserManager<ApplicationUser> UserManager;
            private readonly IAuthenticationManager AuthenticationManager;   
     public AccountController(IUserStore<ApplicationUser> userStore, IAuthenticationManager authManager)
                {
                    UserManager = new UserManager<ApplicationUser>(userStore);
                    AuthenticationManager = authManager;
                }

登录方式

private async Task SignInAsync(ApplicationUser user, bool isPersistent)
            {
                AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); //identity.IsAuthenticated is true
                AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity); //User.Identity.IsAuthenticated is false
            }

问题: 请检查上面的注释行,identity.IsAuthenticated 是真的(没关系)但 User.Identity.IsAuthenticated 仍然是假的。

如何在 HttpContext.User.Identity 中更新这个身份?

【问题讨论】:

    标签: c# asp.net-mvc dependency-injection asp.net-identity unity-container


    【解决方案1】:

    startup.Auth.cs 中的ConfigureAuth() 未被调用。调用这个函数解决了这个问题

    【讨论】:

      猜你喜欢
      • 2019-05-02
      • 1970-01-01
      • 2012-04-18
      • 2017-03-27
      • 1970-01-01
      • 2021-11-06
      • 2014-08-17
      • 1970-01-01
      • 2012-12-13
      相关资源
      最近更新 更多