HttpContext.GetOwinContext().GetUserManager<AppRoleManager>() 返回空值



我使用ASP.NET Identity 2创建角色,但HttpContext.GetOwinContext().GetUserManager<AppRoleManager>()的结果为null。

然后我无法创建这个角色。

我该如何解决这个问题?

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

我的控制器:

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

很可能您错过了为OwinContext提供创建ApplicationUserManager的方法
为此,您需要在public void Configuration(IAppBuilder app) 中包含这些

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

这将使用OwinContext注册创建UserManagerRoleManager的委托,然后您才能在控制器中调用这些委托。

我知道这是一篇旧文章,但我想与其他人分享我的研究,对于这个问题,我创建了分部类,并在那里添加了我所有的owin参考:

public partial class Startup
    {
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(IdentityModels.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
app.CreatePerOwinContext<AppRoleManager>(AppRoleManager.Create);
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.  
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                validateInterval: TimeSpan.FromMinutes(30),
                regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });

        }
    }

然后我在其他部分启动中使用这种方法:

  public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }

相关内容

  • 没有找到相关文章