简体   繁体   English

检查要显示的用户角色

[英]Checking User Roles to Display

I recently added Identity to my ASP.NET project, but I'm having trouble checking user roles. 我最近将身份添加到我的ASP.NET项目中,但是在检查用户角色时遇到了麻烦。

I originally create my Admin role in Startup.cs: 我最初在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");
            }
        }
}

In my UserController.cs, I have a function to check if the user is an 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;
}

However, I can't seem to find a way to access the isAdminUser() function from both my Views and my Controllers. 但是,我似乎找不到从我的视图和控制器访问isAdminUser()函数的方法。

I've done a little bit of research the IsUserInRole() function, but when I tried: 我已经对IsUserInRole()函数做了一些研究,但是当我尝试时:

@if (Roles.IsUserInRole(User.Identity.Name, "Admin")) { Html.ActionLink("Edit", "Edit", new { id=item.GuestID }); }

The if statement always returns false. if语句始终返回false。

Try to use HttpContext.Current.User.IsInRole("Admin"); 尝试使用HttpContext.Current.User.IsInRole("Admin"); as Roles.IsUserInRole related to old membership provider under System.Web.Security namespace and need roleManager provider configuration in web.config . 作为Roles.IsUserInRoleSystem.Web.Security命名空间下的旧成员资格提供程序相关,并且需要在web.config配置roleManager提供程序。

@if(HttpContext.Current.User.IsInRole("Admin")) 
{
    Html.ActionLink("Edit", "Edit", new { id = item.GuestID });
}

Another way is to use UserManager 另一种方法是使用UserManager

userManager.IsInRole("userId","Admin")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM