gpt4 book ai didi

c# - 获取用户角色的最快方法

转载 作者:行者123 更新时间:2023-11-30 12:46:30 24 4
gpt4 key购买 nike

你有一个 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>>() 

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

如果您更新到 nightly 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;
}
}

关于c# - 获取用户角色的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19992935/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com