【问题标题】:Identity API 2.0 Check if user is admin role on ViewIdentity API 2.0 检查用户是否是 View 的管理员角色
【发布时间】:2015-05-14 23:36:39
【问题描述】:

在脚手架局部视图_Layout.cshtml 内定义了应用的导航栏。我想对其进行修改,以便仅当登录用户为 "Admin" 时才显示某些链接。

在我的Configuration.cs 迁移文件的Seed() 方法中,定义如下:

bool AddUserAndRole(ApplicationDbContext context) {
        IdentityResult ir;

        var rm = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
        ir = rm.Create(new IdentityRole("Admin"));

        var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));

        var user = new ApplicationUser() { UserName = "admin", FirstName = "System", LastName = "Administrator" };
        ir = um.Create(user, "admin");

        if(ir.Succeeded == false) {
            return ir.Succeeded;
        }

        ir = um.AddToRole(user.Id, "Admin");

        return ir.Succeeded;
    }

如您所见,有一个名为“Admin”的角色,并将新创建的用户添加到该角色中。

话虽如此,我在_Layout.cshmtl 中尝试了几种方法来尝试确定当前用户是否为"Admin"

@if(Roles.IsUserInRole(User.Identity.Name, "Admin")) { }

@if (User.IsInRole("Admin")) { }

但似乎没有一个有效。我该怎么做?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-5 asp.net-identity-2


    【解决方案1】:
    @if (User.IsInRole("Admin"))
        {
             <li>@Html.ActionLink("Link Text", "Controller", "Action")</li>
        }
    

    这对我有用。

    【讨论】:

    • 问题是密码“admin”不起作用,需要有大写字母和数字,所以没有创建角色,因为它没有成功
    猜你喜欢
    • 2014-05-27
    • 1970-01-01
    • 2018-02-02
    • 1970-01-01
    • 2015-05-19
    • 1970-01-01
    • 2018-04-29
    • 2014-10-28
    • 2016-08-01
    相关资源
    最近更新 更多