Reputation: 15275
U have an ASP.Net MVC 5 website and I want to retrieve current user's roles (if any) and act on them accordingly. I've noticed some changes, even after the Beta version of VS 2013 in the template. I'm currently using this code:
//in Utilities.cs class
public static IList<string> GetUserRoles(string id)
{
if (id == null)
return null;
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new AppContext()));
return UserManager.GetRoles(id);
}
//and I call it like this:
var roles = Utilities.GetUserRoles(User.Identity.GetUserId());
Is this the best approach? If not, what is?
I'm using this to create the roles and add users to the role:
RoleManager.Create(new IdentityRole("admin"));
if (um.Create(user, password).Succeeded)
{
UserManager.AddToRole(user.Id, role);
}
Upvotes: 4
Views: 4779
Reputation: 28200
That should work, but just a heads up, in the 1.1-alpha1 bits, we've added middleware and extension methods so the UserManager will be created once per request and can be reused, so instead of creating a new UserManager in your app code, you will be able to call:
owinContext.GetUserManager<UserManager<MyUser>>()
which should also guarantee you get the same instance of your entities since you aren't creating different db contexts.
If you update to the nightly 1.1 alpha bits, you will need to add this to the top of your Startup.Auth.cs to register the new middleware which creates a userManager:
// Configure the UserManager
app.UseUserManagerFactory(new UserManagerOptions<ApplicationUser>()
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true,
DataProtectionProvider = app.GetDataProtectionProvider(),
Provider = new UserManagerProvider<ApplicationUser>()
{
OnCreateStore = () => new UserStore<ApplicationUser>(new ApplicationDbContext())
}
});
And then you can change the AccountController to pick it up from the context:
private UserManager<ApplicationUser> _userManager;
public UserManager<ApplicationUser> UserManager {
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUser>();
}
private set
{
_userManager = value;
}
}
Upvotes: 1