tutorial net mvc implement framework existing asp c# asp.net-identity identity roles owin

c# - mvc - implement identity asp net



HttpContext.GetOwinContext(). GetUserManager<AppRoleManager>() devuelve null (2)

He usado ASP.NET Identity 2 para crear un rol, pero el resultado de HttpContext.GetOwinContext().GetUserManager<AppRoleManager>() fue nulo.

Entonces no pude crear el papel.

¿Como puedó resolver esté problema?

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

Mi controlador:

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


Lo más probable es que haya perdido a OwinContext la manera de crear ApplicationUserManager.
Para eso necesitarás tener esto en tu public void Configuration(IAppBuilder app)

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

Esto registrará a los delegados que crean UserManager y RoleManager con OwinContext y solo después de eso puede volver a llamar a estos en sus controladores.


Sé que es una publicación antigua, pero quiero compartir mis investigaciones con otros, para este problema creé una clase parcial y agregué todas mis referencias de owin allí:

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

Luego utilizo este método en otro inicio parcial:

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