Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpContext.GetOwinContext().GetUserManager<AppRoleManager>() return null

I've used ASP.NET Identity 2 for creating role but the result of HttpContext.GetOwinContext().GetUserManager<AppRoleManager>() was null.

Then I couldn't create the role.

How can I solve this problem?

public class MVCController : Controller
{
    public MVCController()
    {

    }
    public AppRoleManager RoleManager // returns null ?!
    {
        get
        {
            return HttpContext.GetOwinContext().GetUserManager<AppRoleManager>();
        }
    }
    public User CurrentUser
    {
        get
        {
            string currentUserId = User.Identity.GetUserId();
            User currentUser = DataContextFactory.GetDataContext().Users.FirstOrDefault(x => x.Id.ToString() == currentUserId);
            return currentUser;
        }
    }
    public IAuthenticationManager AuthManager
    {
        get
        {

            return HttpContext.GetOwinContext().Authentication;
        }
    }
    public AppUserManager UserManager
    {
        get
        {
            return HttpContext.GetOwinContext().GetUserManager<AppUserManager>();
        }
    }
} 

My Controller:

public class RoleAdminController : MVCController
{
    [HttpPost]
    public async Task<ActionResult> CreateRole([Required]string name)
    {
        if (ModelState.IsValid)
        {
            if (RoleManager != null) // RoleManager is null, why?!
            {
                IdentityResult result = await RoleManager.CreateAsync(new Role { Name = name });
                if (result.Succeeded)
                {
                    return RedirectToAction("Index");
                }
                else
                {
                    AddErrorsFromResult(result);
                }
            }
        }
        return View(name);
    }
}

AppRoleManager:

public class AppRoleManager : RoleManager<Role, int>, IDisposable
{
    public AppRoleManager(RoleStore<Role, int, UserRole> store)
        : base(store)
    {
    }
    public static AppRoleManager Create(IdentityFactoryOptions<AppRoleManager> options, IOwinContext context)
    {
        return new AppRoleManager(new RoleStore<Role, int, UserRole>(DataContextFactory.GetDataContext()));
    }
}
like image 824
Roohi Avatar asked Oct 13 '14 19:10

Roohi


1 Answers

Most likely you have missed giving OwinContext the way to create ApplicationUserManager.
For that you'll need to have these in your public void Configuration(IAppBuilder app)

app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<AppRoleManager>(AppRoleManager.Create);

This will register delegates that create UserManager and RoleManager with OwinContext and only after that you can call these back in your controllers.

like image 170
trailmax Avatar answered Nov 06 '22 05:11

trailmax