HttpContext.GetOwinContext().GetUserManager<AppRoleManager>() 返回 null。

18

我使用了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()));
    }
}

1
尝试使用 HttpContext.GetOwinContext().Get<AppRoleManager>(); - trailmax
2
@trailmax:返回 null。 - x19
获取和获取UserManager之间有什么区别? - mejdev
2个回答

37

很可能您忘了给OwinContext提供创建ApplicationUserManager的方法。
为此,您需要在public void Configuration(IAppBuilder app)中添加以下内容:

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

这将使用委托函数在OwinContext中创建UserManagerRoleManager,只有在那之后您才能在控制器中调用它们。


1
@Jahan 抱歉,我更正了我的答案,第二行应该是将 AppRoleManager 作为泛型参数。 - trailmax
1
方法位置:项目>startup.cs - Vasil Valchev
3
AppRoleManager 不存在。 - Vasil Valchev
当我添加了这些代码行但仍然有一个空的UserManager时,该去哪里查看?我在调试时检查过:这些代码行在启动时被调用。当我想要访问ApplicationUserManager时,我只得到了一个null。有任何想法吗? - Augustin Bocken
1
@AugustinBocken ApplicationUserManager.Create 返回任何内容吗? - trailmax
显示剩余9条评论

0

我知道这是一篇旧文章,但我想与其他人分享我的研究成果。对于这个问题,我创建了一个部分类,并在其中添加了所有的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);
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接