加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 21:58:42 所属栏目:百科 来源:网络整理
导读:你有一个ASP.Net MVC 5网站,我想检索当前用户的角色(如果有的话),并相应地采取行动.即使在模板中使用VS 2013的Beta版之后,我也注意到了一些变化.我目前正在使用此代码: //in Utilities.cs class public static IListstring GetUserRoles(string id) { if (i
你有一个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;
        }
    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读