2013-10-31 35 views
72

很少有關於使用新的Asp.net身份安全框架的文檔。在Asp.net中創建角色身份MVC 5

我拼湊出了我可以嘗試創建新角色並將其添加到用戶的任務。我試過如下:Add role in ASP.NET Identity

它看起來像它可能已經得到了從這個博客的信息:building a simple to-do application with asp.net identity and associating users with to-does

我添加的代碼到運行每當模型更改數據庫初始化程序。它無法與以下錯誤RoleExists功能:

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

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)); 
    } 
} 

任何幫助表示讚賞。

回答

19

確認你有以下的MyContext類的簽名

public class MyContext : IdentityDbContext<MyUser>

或者

public class MyContext : IdentityDbContext

的代碼爲我工作,沒有任何修飾!

+4

謝謝大家的回覆。一切都在工作。檢查背景使我朝着正確的方向前進。當創建asp.net標識時,它會創建一個新的上下文(ApplicationDbContext),它擴展了IdentityDbContext。在我的代碼中,我引用了沒有擴展IdentityDbContext的原始上下文。如果其他人有這個問題,請檢查您的上下文並仔細檢查您的APP_DATA目錄,以確保您不會意外創建兩個數據庫。 – colbyJax

64

這裏,我們去:

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); 

    } 
+2

這對我有幫助,特別是因爲我沒有使用遷移。我正在使用DropCreateDatabaseAlways。 – Ciwan

+0

我的問題是我使用了錯誤的上下文。我創建了兩個連接字符串,一個名爲'IdentityDbContext',另一個我使用自定義上下文,所以當我使用你的建議'AppilcationDbContext()'時,它就起作用了。 – megamaiku

7

上彼得斯代碼的改進上面,你可以使用這個:

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

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

下面是說明如何創建角色,修改角色的完整文章,刪除角色和使用ASP.NET身份管理角色。這也包括用戶接口,控制器等方法

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

希望這helpls

感謝

+1

您的博客很好,但過時了,您可以更新帳戶控制器 – aggie

+0

它已經爲ASP.NET MVC 5(你正在尋找什麼樣的更新阿吉?)。您可以從文章中指定的GitHub鏈接下載源代碼。 –

+1

其中一些函數最近從2.2.0開始不推薦使用。 1)我可以在當前版本中使用相同的代碼2)如何將主鍵從Guid更改爲電子郵件3)有關如何將身份驗證與身份集成的任何建議,請點擊http://j.mp/1nohaHe – aggie

0

我想分享另一種解決方案添加角色:

<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" /> 
} 

控制器:

[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(); 
    } 
3

我的應用程序在啓動時掛起,當我使用Peter Stulinski & Dave Gordon的代碼示例與EF 6.0。我改變:

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

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

種子方法時,你不希望實例化ApplicationDBContext的另一個實例,它是有道理的。這可能是由我的ApplicationDbContext

+0

這就是正確他們搬到EF 6的角色商店 –

2

角色構造視圖模型

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

控制方法

[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(); 
    } 
14

Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());ASP.NET 5 rc1-final事實複合,我沒下列內容:

創建ApplicationRoleManager(與ApplicationUser c相似通過模板Startup.cs reated)

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) 
    { 
    } 
} 

ConfigureServices,我增加一條,作爲RoleManager

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

創建新角色,從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(); 
    ... 
} 

現在,規則被分配給用戶

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

或者在Authorize屬性

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

這是驚人的!感謝更新。 –

+0

'services.AddIdentity ()。AddRoleManager ()'我無法直接將它添加到'services'。 –

+2

@AlexC,對不起,我的壞。我儘量保持簡單,並刪除了AddIdentity。固定。 – nothrow

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

我使用創建角色低於,在代碼中它們分配給用戶,也列出的方法使用。下面的代碼在migrations文件夾中的「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();