2017-02-17 110 views
-1

我遇到了用戶角色的問題。我想在註冊期間給角色ID = 1。我正在使用Visual Studio註冊站點。我有兩個SQL表,帶有我的角色的AspNetRoles和帶有UserID和RoleId的AspNetRoles。但我不知道如何在註冊過程中發揮作用。我的代碼:註冊用戶角色

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

回答

0

您可以使用UserManager上的AddToRole()方法來執行此操作。我不認爲它需要一個ID,但你需要角色的名字。

var roleresult = UserManager.AddToRole(user.Id, "Administrator"); 
相關問題