【问题标题】:Checking User Roles to Display检查要显示的用户角色
【发布时间】: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


    【解决方案1】:

    尝试在System.Web.Security命名空间下使用HttpContext.Current.User.IsInRole("Admin");作为与旧会员提供者相关的Roles.IsUserInRole,并且需要在web.config中配置roleManager提供者。

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

    另一种方法是使用UserManager

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

    【讨论】:

    • 那没用,但我想你可能正在做点什么。我现在注意到我有 2 个数据库上下文;上面看到的 ApplicationDbContext 和我的控制器中使用的不同的 databaseEntites 上下文。这可能是问题的根源吗?
    • 您能否检查Admin 是否已保存到您的数据库以及用户是否与此角色正确关联
    • @shrug 可能由于不同的原因而无法正常工作。这是正确的答案 - 要点Roles.IsUserInRole属于旧框架,不应该在这里使用。
    猜你喜欢
    • 2022-10-16
    • 2016-09-09
    • 2020-08-04
    • 2011-11-05
    • 2020-02-12
    • 2016-01-10
    • 1970-01-01
    • 2016-08-28
    • 2013-11-10
    相关资源
    最近更新 更多