微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 获得用户角色的最快方式

你有一个ASP.Net MVC 5网站,我想检索当前用户的角色(如果有的话),并相应地采取行动.即使在模板中使用VS 2013的Beta版之后,我也注意到了一些变化.我目前正在使用此代码

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

这是最好的方法吗?如果不是,那是什么?

编辑:

我正在使用它来创建角色并将用户添加到角色:

RoleManager.Create(new IdentityRole("admin"));
if (um.Create(user,password).Succeeded)
{
   UserManager.AddToRole(user.Id,role);
}

解决方法

这应该是有用的,但只是抬头,在1.1-alpha1位,我们添加了中间件和扩展方法,因此每个请求将创建一次UserManager并可以重复使用,因此不要在应用代码中创建新的UserManager,你可以打电话:

owinContext.GetUserManager<UserManager<MyUser>>()

这也应该保证您获得实体的相同实例,因为您没有创建不同的数据库上下文.

如果更新到每晚1.1 alpha位,则需要将其添加到Startup.Auth.cs的顶部以注册创建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())
            }
        });

然后你可以改变AccountController从上下文中选择它:

private UserManager<ApplicationUser> _userManager;
    public UserManager<ApplicationUser> UserManager {
        get
        {
            return _userManager ?? HttpContext.GetowinContext().GetUserManager<ApplicationUser>();
        }
        private set
        {
            _userManager = value;
        }
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐