Quantcast
Channel: Security
Viewing all articles
Browse latest Browse all 4737

Try to add a username to a role using .net 4.5 asp.net Identity

$
0
0
<div class="userinput">

This is a question about the new way of handling authentication and membership which is based on asp.net Identity

I have just create a web application project with web forms and make some test.

Here I have a piece of code. If I put a breakpoint at this statement userManager.AddToRole

I can see that in database table AspNetUsers I have my name tony there. If I look in table AspNetRoles I have role MyRole there.

So It would be fine to do this statement     
userManager.AddToRole("tony", "MyRole");

because I have the name tony in AspNetUsers and I have MyRole in AspNetRoles

But I get exception saying "UserId not found" but name tony really exist in table AspNetUsers why do I get exception ?

 protected void Page_Load(object sender, EventArgs e)
        {
            var context = new ApplicationDbContext();
            var roleManager = new RoleManager<IdentityRole>(
                new RoleStore<IdentityRole>(context));
            
            if (!roleManager.RoleExists("MyRole"))
            {
                roleManager.Create(new IdentityRole("MyRole"));
            }

            var userManager = new UserManager<ApplicationUser>(
                new UserStore<ApplicationUser>(context));

            try
            {
                userManager.AddToRole("tony", "MyRole"); //AspNetUsers(tony), AspNetRoles(MyRole)
            }
            catch (Exception ex)
            {
            }
        }

//Tony

</div>

Viewing all articles
Browse latest Browse all 4737

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>