如何在MVC 5中使用用户身份中的角色

Mos*_*afa 8 asp.net-mvc user-roles asp.net-mvc-5 asp.net-identity

我想在mvc 5中使用asp.net useridentity,我执行以下步骤:

1)创建一个mvc项目.

2)创建我自己的数据库并更改web.config表单中的连接字符串:to:

3)我运行项目并创建一个新用户将相关表添加到我的数据库.

4)我想在accountControler中注册像此代码的用户之后为用户添加一个角色:

public async Task<ActionResult> Register(RegisterViewModel model)
  {
     if (ModelState.IsValid)
        {
            var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };

            IdentityResult result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                //******************* Add Role To User  **************
                if (!Roles.RoleExists("Member"))
                    Roles.CreateRole("Member");
                Roles.AddUserToRole(model.Email, "Member");
                //****************************************************

                await SignInAsync(user, isPersistent: false);
                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                return RedirectToAction("Index", "Home");
            }
            else
            {
                AddErrors(result);
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }
Run Code Online (Sandbox Code Playgroud)

5)我补充说

<roleManager enabled="true">
Run Code Online (Sandbox Code Playgroud)

成:

<system.web></system.web>
Run Code Online (Sandbox Code Playgroud)

当我创建一个新用户时,我的用户注册得很好但用户没有添加到角色,当我这样做时VS在App_Data中创建一个名为"ASPNETDB.MDF"的新数据库.所以我发现了一篇新文章,解释了web.config中的角色提供者设置和:

6)我补充说

<roleManager enabled="true">
  <providers>
    <clear/>
    <add name="AspNetSqlRoleProvider" connectionStringName="DefaultConnection" applicationName="/" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
  </providers>
</roleManager>
Run Code Online (Sandbox Code Playgroud)

进入:

<system.web></system.web>
Run Code Online (Sandbox Code Playgroud)

但是当我想注册新用户时,我发现了这个错误:

找不到存储过程'dbo.aspnet_CheckSchemaVersion'.

现在我认为我的问题是当我执行第3步时它不会完全创建用户身份数据库和存储过程!我对MVC 5使用的角色是真的吗?请帮我解决这个问题!

Bel*_*ash 9

当你写作

 !Roles.RoleExists("Member") 
Run Code Online (Sandbox Code Playgroud)

你没有使用ASP.NET身份!相反,你应该使用ApplicationRole它扩展IdentityRole

此外,您无需AspNetSqlRoleProvider在配置文件中告知.Asp.Net Identity是不同的东西.在Asp.Net Identity中,有一个ApplicationRoleManager在App_Start文件夹中命名的类.

您不应该使用Asp.Net Identity,就好像它是旧的简单成员资格一样.

或者,检查身份证的beta版(这意味着可能会发生变化)以了解有关如何进行身份识别的更多信息.

以下是如何开始:

  • 创建一个新项目:选择Empty template(Not MVC not WebForm)
  • 通过nuget安装Asp.Net标识样本

    PM> Install-Package Microsoft.AspNet.Identity.Samples -Pre
    
    Run Code Online (Sandbox Code Playgroud)
  • 编辑命名空间以匹配旧的项目命名空间
  • 如果要将旧项目中的某些文件夹复制到新项目,请复制(控制器,视图,...)而不是配置文件.

您可以在此处创建角色,如下所示:

            var role = new IdentityRole("roleName");
            var roleresult = await RoleManager.CreateAsync(role);
Run Code Online (Sandbox Code Playgroud)

并创建用户并将其添加到您将使用此角色的特定角色

           var user = new ApplicationUser
            {
                UserName = "tresorunikin",
                Email = "tresorunikin@bellashada.com",
                EmailConfirmed =true
            };

            var userResult = await UserManager.CreateAsync(user, "123@Strong.Password");
            if(userResult.Succeeded){
            string[] roles =new string[]{"admin","seller","other"};
           var roleResult = await UserManager.AddToRolesAsync(user.Id, roles);
            if(roleResult.Succeeded){
                //Here, user has been added to roles
             }
           }
Run Code Online (Sandbox Code Playgroud)

所有这些都是由Pranav RastogiMicrosoft的一个Identity团队为您完成的.

请注意,使用这些示例,您将定位比System.Web.Mvc 5.0.0.0更新的System.Web.Mvc的新(测试版)版本如果我记得很好,测试版是System.Web.MVC 5.0.1.2或类似的东西那

要了解有关身份的更多信息, 请单击

更新 样本中的版本是:System.Web.Mvc 5.2.1.0