[英]Fastest way to get user's roles
U have an ASP.Net MVC 5 website and I want to retrieve current user's roles (if any) and act on them accordingly. 你有一个ASP.Net MVC 5网站,我想检索当前用户的角色(如果有的话),并相应地采取行动。 I've noticed some changes, even after the Beta version of VS 2013 in the template. 即使在模板中使用VS 2013的Beta版之后,我也注意到了一些变化。 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);
}
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: 这应该是有用的,但只是抬头,在1.1-alpha1位,我们添加了中间件和扩展方法,因此每个请求将创建一次UserManager并且可以重复使用,因此不要在应用代码中创建新的UserManager ,你可以打电话:
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: 如果更新到每晚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())
}
});
And then you can change the AccountController to pick it up from the context: 然后你可以改变AccountController从上下文中选择它:
private UserManager<ApplicationUser> _userManager;
public UserManager<ApplicationUser> UserManager {
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUser>();
}
private set
{
_userManager = value;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.