Search code examples
c#asp.net-web-apiasp.net-identityowinasp.net-identity-2

Successfully implementing custom UserManager<IUser> in Identity 2.0


I'm trying to navigate the black hole that is the custom implementation of Identity Membership. My goal right now is simply to get this line from my ApiController to correctly retrieve my UserManager:

public IHttpActionResult Index()
{
    var manager = HttpContext.Current.GetOwinContext().GetUserManager<UserManager<MyUser,int>>();
    //manager is null
}

Here's my setup. In my Startup's Configuration I set up the WebApi and add my OwinContext:

app.CreatePerOwinContext<UserManager<MyUser,int>>(Create);

My Create method:

public static UserManager<User,int> Create(IdentityFactoryOptions<UserManager<MyUser,int>> options, IOwinContext context)
{
   return new UserManager<MyUser,int>(new UserStore(new DbContext()));
}

the rest is the most basic implementation I can make.

MyUser:

public class MyUser : IUser<int>
{
    public int Id { get; set; }
    public string UserName { get; set; }
}

MyUserStore:

 public class MyUserStore : IUserStore<MyUser,int>
 {
    private IdentityDbContext context;
    public MyUserStore(IdentityDbContext c)
    {
       context = c;
    }

    //Create,Delete, etc implementations
 }

MyDbContext:

 public class MyDbContext : IdentityDbContext
 {
     public MyDbContext() : base("Conn")
     {

     }
 }

This is all for the sake of learning how Identity works, which I'm pretty convinced no one actually knows. I want to be able to fully customize my Users and Roles eventually, avoiding Microsoft's IdentityUser.

Again, my issue right now is that in my controller, I am getting null when trying to retrieve my UserManager.

Any and all help is greatly appreciated.


Solution

  • I had several errors, but the main one was that my Startup class looked like :

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseWebApi(new WebApiConfig());
    
            app.CreatePerOwinContext(MyDbContext.Create);
            app.CreatePerOwinContext<MyUserManager>(MyUserManager.Create);
        }
    }
    

    Of course, the OWIN pipeline will plug my dependencies after firing off the WebAPI calls. Switching those around was my main problem.

    In addition, I finally found this great guide way down in my Google search. It answers pretty much everything I was getting at. I needed to implement a concrete class that was a UserManager<MyUser,int>

    I hope this is able to help someone later on.