我在控制器操作中调用了以下内容:
private ApplicationUserManager ApplicationUserManager
=> HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
我的IdentityConfig如下:
internal class IdentityConfig
{
public void Configuration(IAppBuilder appBuilder)
{
appBuilder.CreatePerOwinContext(ApplicationIdentityDbContext.Create);
appBuilder.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
appBuilder.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
var cookieAuthenticationOptions = new CookieAuthenticationOptions
{
AuthenticationType =
DefaultAuthenticationTypes
.ApplicationCookie,
LoginPath =
new PathString("/Home/Login")
};
appBuilder.UseCookieAuthentication(cookieAuthenticationOptions);
}
}
我可以单步执行并查看调用配置并调用Create
方法并且不返回null
。
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options,
IOwinContext context)
{
var db = context.Get<ApplicationIdentityDbContext>();
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(db));
manager.PasswordValidator = new PasswordValidator();
return manager;
}
当我得到ApplicationUserManager
时,它为空。
public class AccountController : Controller
{
private ApplicationUserManager ApplicationUserManager
=> HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
var user = await ApplicationUserManager.FindAsync(model.Username, model.Password); // <- Null reference exception
// ...
}
}
我在这里错过了什么?
答案 0 :(得分:2)
修复是令人不满意的。
卸载与Owin和Identity相关的所有Nuget包,注释掉所有未构建的包,然后重新启动Visual Studio,清理并重建,然后重新安装包。
当它们安装时,出于某种原因它们不是最新的,所以你需要返回并升级它们。
现在再次取消注释并重建。突然,它有效!
不是一个好的解决方案。