How to use Roles in user identity in MVC 5

后端 未结 1 601
伪装坚强ぢ
伪装坚强ぢ 2021-02-04 15:41

I want to use asp.net useridentity in mvc 5, I do these steps:

1) create a mvc project.

2) create my own database and change the connectionstring in web.config f

相关标签:
1条回答
  • 2021-02-04 16:17

    When you write

     !Roles.RoleExists("Member") 
    

    you are not using ASP.NET Identity! instead, you should use ApplicationRole so it extends the IdentityRole class

    In addition, you don't need to tell the AspNetSqlRoleProvider in your config file. Asp.Net Identity is something different. In Asp.Net Identity there is a class named ApplicationRoleManager in the App_Start folder.

    You should not use Asp.Net Identity as if it was the old simple membership.

    Alternatively, check the beta(which means things may change) version of Identity to learn more on how to do in Identity.

    Here is how to start :

    • Create a new project : Choose Empty template (Not MVC not WebForm)
    • Install the Asp.Net identity sample via nuget

      PM> Install-Package Microsoft.AspNet.Identity.Samples -Pre
      
    • edit namespace to match your old project namespace
    • If you want to copy some folders from your old project to the new project, copy your (Controllers, Views,... ) not the config files.

    Here you can create roles as follows:

                var role = new IdentityRole("roleName");
                var roleresult = await RoleManager.CreateAsync(role);
    

    and to create and add a user to specific roles you will use this

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

    All these are done for you by Pranav Rastogi, one of the Identity team at Microsoft.

    Note that with these samples you target a new (beta) version of System.Web.Mvc that is newer than System.Web.Mvc 5.0.0.0 If I remember well the beta version is System.Web.MVC 5.0.1.2 or something like that

    To Learn More about Identity click here

    UPDATES The Version in the samples is: System.Web.Mvc 5.2.1.0

    0 讨论(0)
提交回复
热议问题