Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 正在检查要显示的用户角色_Asp.net Mvc_Asp.net Identity 2 - Fatal编程技术网

Asp.net mvc 正在检查要显示的用户角色

Asp.net mvc 正在检查要显示的用户角色,asp.net-mvc,asp.net-identity-2,Asp.net Mvc,Asp.net Identity 2,我最近在ASP.NET项目中添加了标识,但在检查用户角色时遇到了问题 我最初在Startup.cs中创建管理员角色: private void createRolesandUsers() { ApplicationDbContext context = new ApplicationDbContext(); var roleManager = new RoleManager<IdentityRole>(new RoleStore<Identit

我最近在ASP.NET项目中添加了标识,但在检查用户角色时遇到了问题

我最初在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");
            }
        }
}

if语句总是返回false。

尝试使用
HttpContext.Current.User.IsInRole(“Admin”)
as
Roles.IsUserInRole
与命名空间下的旧成员资格提供程序相关,并且需要
web.config
中的
rolemager
提供程序配置

@if(HttpContext.Current.User.IsInRole("Admin")) 
{
    Html.ActionLink("Edit", "Edit", new { id = item.GuestID });
}
另一种方法是使用
UserManager

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

尝试使用HttpContext.Current.User.IsInRole(“Admin”)as
Roles.IsUserInRole
与命名空间下的旧成员资格提供程序相关,并且需要
web.config
中的
rolemager
提供程序配置

@if(HttpContext.Current.User.IsInRole("Admin")) 
{
    Html.ActionLink("Edit", "Edit", new { id = item.GuestID });
}
另一种方法是使用
UserManager

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

那不管用,但我想你可能知道些什么。我注意到现在我有2个数据库上下文;上面看到的ApplicationDbContext和我的控制器中使用的另一个databaseEntites上下文。这可能是问题的根源吗?您能否检查是否已将
Admin
保存到您的数据库中,并且用户是否与此正确关联role@shrug这可能是由于不同的原因而不起作用。这是正确的答案-要点
角色。IsUserInRole
属于较旧的框架,不应在此处使用。这不起作用,但我认为您可能了解一些情况。我注意到现在我有2个数据库上下文;上面看到的ApplicationDbContext和我的控制器中使用的另一个databaseEntites上下文。这可能是问题的根源吗?您能否检查是否已将
Admin
保存到您的数据库中,并且用户是否与此正确关联role@shrug这可能是由于不同的原因而不起作用。这是正确的答案-要点
Roles.IsUserInRole
属于较旧的框架,不应在此处使用。