Search code examples
asp.net-mvcasp.net-identityowinasp.net-identity-2

Owin not returning UserManager


I have the following being called in a controller action:

private ApplicationUserManager ApplicationUserManager
    => HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();

My IdentityConfig looks like:

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);
    }
}

I can step through and see that the config is called and that the Create method is called and doesn't return 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;
}

When I get the ApplicationUserManager though, it is null.

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

        // ...
    }
}

What an I missing here?


Solution

  • The fix was an unsatisfactory one.

    Uninstalling all the Nuget packages relating to Owin and Identity, commenting out everything that doesn't build and then restarting Visual Studio, cleaning and rebuilding and then reinstalling the packages again.

    When they are installed, for some reason they aren't the latest so you need to go back and upgrade them all.

    Now uncomment everything again and rebuild. Suddenly, it works!

    Not a good solution.