如何获取当前登录用户';s在MVC5中的角色ID
本文关键字:MVC5 ID 角色 用户 何获取 获取 登录 | 更新日期: 2023-09-27 18:20:08
众所周知,我们可以通过登录UserId
和UserName
string curentUser = User.Identity.GetUserId();
string currentUserName = User.Identity.GetUserName();
但是如何获取当前用户的roleId
。
您可以获得成员的角色,如下所示:
using System.Web.Security;
string[] roles = Roles.GetRolesForUser(User.Identity.Name);
一个用户可以有多个角色,因此返回值的类型为string[]
。
更新
在ASP.NET Identity 2.0中,可以启用RoleManager
,如下所示:
Models/IdentityModels.cs
public class ApplicationRole : IdentityRole
{
}
App_Start/IdentityConfig.cs
public class ApplicationRoleManager : RoleManager<ApplicationRole, string>
{
public ApplicationRoleManager(IRoleStore<ApplicationRole, string> store)
: base(store)
{
}
public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
{
var dbContext = context.Get<ApplicationDbContext>();
var roleStore = new RoleStore<ApplicationRole>(dbContext);
var manager = new ApplicationRoleManager(roleStore);
// Add some roles (e.g. "Administrator") if needed
if (!manager.Roles.Any(r => r.Name == "Administrator"))
{
manager.Create(new ApplicationRole
{
Name = "Administrator"
});
}
return manager;
}
}
应用程序启动/启动验证
public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager≥(ApplicationUserManager.Create);
// Add this line
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
}
}
Controller/AccountController.cs
public class AccountController : Controller
{
private ApplicationUserManager _userManager;
private ApplicationRoleManager _roleManager;
public AccountController()
{
}
public AccountController(ApplicationUserManager userManager, ApplicationRoleManager roleManager, ApplicationSignInManager signInManager)
{
UserManager = userManager;
RoleManager = roleManager;
SignInManager = signInManager;
}
public ApplicationRoleManager RoleManager
{
get
{
return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
}
private set
{
_roleManager = value;
}
}
}
然后,您可以在Account
控制器中从UserId
获取角色。
var roles = UserManager.GetRoles(User.Identity.GetUserId());
在Identity中,您也可以使用UserManager
来访问每个用户角色。由于角色已经实现,因此您不需要任何额外的配置。所以考虑这个例子:
public ActionResult MyAction()
{
userManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
// return a list of current user's roleIDs
var roles = userManager.FindById(User.Identity.GetUserId()).Roles.Select(r => r.RoleId);
}
Microsoft.AspNetCore.Mvc命名空间提供了包含当前登录用户信息的ClaimsPrincipal类型的公共属性User,以获取当前角色idClaimsPrincipal类具有静态方法FindFirstValue,您可以使用该方法,例如。string User.FindFirstValue(ClaimTypes.Role);