HttpContext.GetOwinContext().GetUserManager() return null

后端 未结 2 592
旧时难觅i
旧时难觅i 2021-02-05 10:24

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

Then I could

相关标签:
2条回答
  • 2021-02-05 10:39

    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.

    0 讨论(0)
  • 2021-02-05 10:41

    I know it's old post , but I want to share my researches with others, for this issue I created partial class and add all my owin references there:

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

    then I utilize this method in other partial startup :

      public partial class Startup
        {
            public void Configuration(IAppBuilder app)
            {
                ConfigureAuth(app);
            }
        }
    
    0 讨论(0)
提交回复
热议问题