【发布时间】:2018-04-23 17:24:06
【问题描述】:
我最近在我的 ASP.NET 项目中添加了 Identity,但在检查用户角色时遇到了问题。
我最初在 Startup.cs 中创建了我的管理员角色:
private void createRolesandUsers()
{
ApplicationDbContext context = new ApplicationDbContext();
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
if (!roleManager.RoleExists("Admin"))
{
var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
role.Name = "Admin";
roleManager.Create(role);
var user = new ApplicationUser();
user.UserName = "admin";
user.Email = "admin@tpms.com";
string userPWD = "********";
var chkUser = UserManager.Create(user, userPWD);
if (chkUser.Succeeded)
{
var result1 = UserManager.AddToRole(user.Id, "Admin");
}
}
}
在我的 UserController.cs 中,我有一个函数来检查用户是否是管理员:
public Boolean isAdminUser()
{
if (User.Identity.IsAuthenticated)
{
var user = User.Identity;
ApplicationDbContext context = new ApplicationDbContext();
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var s = UserManager.GetRoles(user.GetUserId());
if (s[0].ToString() == "Admin")
{
return true;
}
else
{
return false;
}
}
return false;
}
但是,我似乎找不到从我的视图和控制器中访问 isAdminUser() 函数的方法。
我对 IsUserInRole() 函数做了一些研究,但是当我尝试时:
@if (Roles.IsUserInRole(User.Identity.Name, "Admin")) { Html.ActionLink("Edit", "Edit", new { id=item.GuestID }); }
if 语句总是返回 false。
【问题讨论】:
标签: asp.net-mvc asp.net-identity-2