C# 在 Asp.net Identity MVC 5 中创建角色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19697226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 15:38:53  来源:igfitidea点击:

Creating Roles in Asp.net Identity MVC 5

c#asp.net-mvc-5asp.net-identity

提问by colbyJax

There is very little documentation about using the new Asp.net Identity Security Framework.

关于使用新的 Asp.net 身份安全框架的文档很少。

I have pieced together what I could to try and create a new Role and add a User to it. I tried the following: Add role in ASP.NET Identity

我已经拼凑了我可以尝试创建一个新角色并向其中添加一个用户的内容。我尝试了以下操作:在 ASP.NET Identity 中添加角色

which looks like it may have gotten the info from this blog: building a simple to-do application with asp.net identity and associating users with to-does

看起来它可能已经从这个博客中获得了信息:构建一个简单的具有 asp.net 身份的待办事项应用程序并将用户与待办事项相关联

I have added the code to a Database Initializer that is run whenever the model changes. It fails on the RoleExistsfunction with the following error:

我已将代码添加到每当模型更改时运行的数据库初始化程序中。它在RoleExists功能上失败并出现以下错误:

System.InvalidOperationExceptionoccurred in mscorlib.dll The entity type IdentityRole is not part of the model for the current context.

System.InvalidOperationExceptionmscorlib.dll 中发生的实体类型 IdentityRole 不是当前上下文模型的一部分。

protected override void Seed (MyContext context)
{
    var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); 
    var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));

    // Create Admin Role
    string roleName = "Admins";
    IdentityResult roleResult;

    // Check to see if Role Exists, if not create it
    if (!RoleManager.RoleExists(roleName))
    {
        roleResult = RoleManager.Create(new IdentityRole(roleName));
    }
}

Any help is appreciated.

任何帮助表示赞赏。

采纳答案by jd4u

Verify you have following signature of your MyContextclass

验证您有以下MyContext班级签名

public class MyContext : IdentityDbContext<MyUser>

public class MyContext : IdentityDbContext<MyUser>

Or

或者

public class MyContext : IdentityDbContext

public class MyContext : IdentityDbContext

The code is working for me, without any modification!!!

代码对我有用,没有任何修改!!!

回答by Piotr Stulinski

Here we go:

开始了:

var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));


   if(!roleManager.RoleExists("ROLE NAME"))
   {
      var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
      role.Name = "ROLE NAME";
      roleManager.Create(role);

    }

回答by Dave Gordon

As an improvement on Peters code above you can use this:

作为对上述 Peters 代码的改进,您可以使用以下代码:

   var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));

   if (!roleManager.RoleExists("Member"))
            roleManager.Create(new IdentityRole("Member"));

回答by Sheo Narayan

Here is the complete article describing how to create role, modify roles, delete roles and manage roles using ASP.NET Identity. This also contains User interface, controller methods etc.

这是描述如何使用 ASP.NET Identity 创建角色、修改角色、删除角色和管理角色的完整文章。这还包含用户界面、控制器方法等。

http://www.dotnetfunda.com/articles/show/2898/working-with-roles-in-aspnet-identity-for-mvc

http://www.dotnetfunda.com/articles/show/2898/working-with-roles-in-aspnet-identity-for-mvc

Hope this helpls

希望这有帮助

Thanks

谢谢

回答by JoshYates1980

I wanted to share another solution for adding roles:

我想分享另一个添加角色的解决方案:

<h2>Create Role</h2>

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<span class="label label-primary">Role name:</span>
<p>
    @Html.TextBox("RoleName", null, new { @class = "form-control input-lg" })
</p>
<input type="submit" value="Save" class="btn btn-primary" />
}

Controller:

控制器:

    [HttpGet]
    public ActionResult AdminView()
    {
        return View();
    }

    [HttpPost]
    public ActionResult AdminView(FormCollection collection)
    {
        var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));

        if (roleManager.RoleExists(collection["RoleName"]) == false)
        {
            Guid guid = Guid.NewGuid();
            roleManager.Create(new IdentityRole() { Id = guid.ToString(), Name = collection["RoleName"] });
        }
        return View();
    }

回答by Dane W

My application was hanging on startup when I used Peter Stulinski & Dave Gordon's code samples with EF 6.0. I changed:

当我在 EF 6.0 中使用 Peter Stulinski 和 Dave Gordon 的代码示例时,我的应用程序在启动时挂起。我变了:

var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));

to

var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(**context**));

Which makes sense when in the seed method you don't want instantiate another instance of the ApplicationDBContext. This might have been compounded by the fact that I had Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());in the constructor of ApplicationDbContext

当在种子方法中您不想实例化ApplicationDBContext. 这可能是因为我Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());在构造函数中ApplicationDbContext

回答by Moji

Roles View Model

角色视图模型

public class RoleViewModel
{
    public string Id { get; set; }
    [Required(AllowEmptyStrings = false)]
    [Display(Name = "RoleName")]
    public string Name { get; set; }
}

Controller method

控制器方法

    [HttpPost]
    public async Task<ActionResult> Create(RoleViewModel roleViewModel)
    {
       if (ModelState.IsValid)
       {
           var role = new IdentityRole(roleViewModel.Name);
           var roleresult = await RoleManager.CreateAsync(role);
           if (!roleresult.Succeeded)
           {
               ModelState.AddModelError("", roleresult.Errors.First());
               return View();
           }
           return RedirectToAction("some_action");
       }
       return View();
    }

回答by nothrow

In ASP.NET 5 rc1-final, I did following:

ASP.NET 5 rc1-final,我做了以下:

Created ApplicationRoleManager(in similar manner as there is ApplicationUsercreated by template)

创建ApplicationRoleManager(以与ApplicationUser模板创建类似的方式)

public class ApplicationRoleManager : RoleManager<IdentityRole>
{
    public ApplicationRoleManager(
        IRoleStore<IdentityRole> store,
        IEnumerable<IRoleValidator<IdentityRole>> roleValidators,
        ILookupNormalizer keyNormalizer,
        IdentityErrorDescriber errors,
        ILogger<RoleManager<IdentityRole>> logger,
        IHttpContextAccessor contextAccessor)
        : base(store, roleValidators, keyNormalizer, errors, logger, contextAccessor)
    {
    }
}

To ConfigureServicesin Startup.cs, I added it as RoleManager

ConfigureServicesin Startup.cs,我将其添加为 RoleManager

services.
    .AddIdentity<ApplicationUser, IdentityRole>()
    .AddRoleManager<ApplicationRoleManager>();

For creating new Roles, call from Configurefollowing:

要创建新角色,请从Configure以下位置调用:

public static class RoleHelper
{
    private static async Task EnsureRoleCreated(RoleManager<IdentityRole> roleManager, string roleName)
    {
        if (!await roleManager.RoleExistsAsync(roleName))
        {
            await roleManager.CreateAsync(new IdentityRole(roleName));
        }
    }
    public static async Task EnsureRolesCreated(this RoleManager<IdentityRole> roleManager)
    {
        // add all roles, that should be in database, here
        await EnsureRoleCreated(roleManager, "Developer");
    }
}

public async void Configure(..., RoleManager<IdentityRole> roleManager, ...)
{
     ...
     await roleManager.EnsureRolesCreated();
     ...
}

Now, the rules can be assigned to user

现在,可以将规则分配给用户

await _userManager.AddToRoleAsync(await _userManager.FindByIdAsync(User.GetUserId()), "Developer");

Or used in Authorizeattribute

或者在Authorize属性中使用

[Authorize(Roles = "Developer")]
public class DeveloperController : Controller
{
}

回答by Stephan Ahlf

    public static void createUserRole(string roleName)
    {
        if (!System.Web.Security.Roles.RoleExists(roleName))
        {
            System.Web.Security.Roles.CreateRole(roleName);
        }
    }

回答by Kevin

the method i Use for creating roles is below, assigning them to users in code is also listed. the below code does be in "configuration.cs" in the migrations folder.

我用于创建角色的方法如下,还列出了将它们分配给代码中的用户。下面的代码确实在迁移文件夹中的“configuration.cs”中。

string [] roleNames = { "role1", "role2", "role3" };
var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));

                IdentityResult roleResult;
                foreach(var roleName in roleNames)
                {
                    if(!RoleManager.RoleExists(roleName))
                    {
                        roleResult = RoleManager.Create(new IdentityRole(roleName));
                    }
                }
                var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
                UserManager.AddToRole("user", "role1");
                UserManager.AddToRole("user", "role2");
                context.SaveChanges();