4

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?

Edit:

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);
}
Community
  • 1
  • 1
Alireza Noori
  • 14,961
  • 30
  • 95
  • 179

1 Answers1

1

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;
        }
    }
Hao Kung
  • 28,040
  • 6
  • 84
  • 93
  • Thank you for this. I really appreciate your help. Also, it's great that someone from the ASP.Net team is answering SO posts and not just MSDN. – Alireza Noori Nov 18 '13 at 21:32
  • just one question though. If I understand correctly, this is not available. Could you please kindly explain what `owinContext` is and how can I use it when it comes out? Or maybe post a link to get me in the right direction? Thanks a lot. – Alireza Noori Nov 18 '13 at 21:36
  • 1
    Its available if you want to try the latest nightly myget feeds. I'll update my answer with what the AccountController/Startup.Auth.cs changes are – Hao Kung Nov 18 '13 at 22:04
  • Awesome. Thanks. Sorry to bug you but 3 quick questions: 1. When will this be in the release, 2. I'm afraid to use alpha if there's a chance that it breaks my website. Can I use just this part or should I upgrade the whole thing? And what is the thing I should upgrade? ASP.Net or the MVC template? 3. When this gets released, should I change anything other than the code above to use this? I mean my project, codes in controller, etc. – Alireza Noori Nov 19 '13 at 00:08
  • 1
    I don't have anything for you in regard to dates, there are schema breaking changes in the Identity.EF package, but the Core should not have introduced any breaking changes. These changes would be in the MVC template, you probably want to wait for now unless you really need something that alpha1 provides. – Hao Kung Nov 19 '13 at 17:54
  • @HaoKung I think there is faster way than this. – Jack Apr 05 '16 at 07:13