【发布时间】: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