-1

I have a problem with user roles. I want to give role ID=1 during registration. I am using Visual Studio registration site. I have two SQL tables, AspNetRoles with my Roles and AspNetRoles with UserID and RoleId. But I don't know how to set a role during registration. My code:

protected void CreateUser_Click(object sender, EventArgs e)
{
    var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
    var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>();
    var user = new ApplicationUser() { UserName = Email.Text, Email = Email.Text };
    IdentityResult result = manager.Create(user, Password.Text);
    if (result.Succeeded)
    {
        SqlConnection con = new SqlConnection();

        con.ConnectionString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=aspnet-WebApplication1-20170217113247;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";


        UserID=....

        string query = "insert into AspNetUserRoles(UserId,RoleId) values ("+ UserID + "," + "1" + ")";

        SqlCommand cmd1 = new SqlCommand(query, con);
        con.Open();
        cmd1.ExecuteNonQuery();
        con.Close();


        signInManager.SignIn( user, isPersistent: false, rememberBrowser: false);
        IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
    }
    else 
    {
        ErrorMessage.Text = result.Errors.FirstOrDefault();
    }
}
icedwater
  • 4,701
  • 3
  • 35
  • 50
MrNobody
  • 1
  • 1
  • 4

1 Answers1

0

You can use the AddToRole() method on the UserManager to do this. I don't think it takes an ID but you'll need the name of the role.

var roleresult = UserManager.AddToRole(user.Id, "Administrator");
Jon
  • 3,230
  • 1
  • 16
  • 28