2017-10-12 12 views
-2

with VS 2015 기본 인증 항목으로 약간의 MVC App을 만들었습니다. 내가 계정 컨트롤러의 등록 행위의 코드를 제외한 아무 것도 변경되지했습니다ASP.Net UserManager AddRoleTo가 작동하지 않습니다.

var context = new ApplicationDbContext(); 
if (ModelState.IsValid) 
{ 
    var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; 
    var result = await UserManager.CreateAsync(user, model.Password); 

    var roleStore = new RoleStore<IdentityRole>(context); 
    var roleManager = new RoleManager<IdentityRole>(roleStore); 

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

    if (!roleManager.RoleExists("Administrator")) 
    { 
     roleManager.Create(new IdentityRole("Administrator")); 
    } 
    if (!roleManager.RoleExists("User")) 
    { 
     roleManager.Create(new IdentityRole("User")); 
    } 

    if (context.Users.Count() == 1) 
    { 
     userManager.AddToRole(user.Id, "Administrator"); 
    } else 
    { 
     try 
     { 
      userManager.AddToRole(user.Id, "User"); 
     } 
     catch (Exception ex) 
     { 
      throw new Exception("Error assigning role: " + ex.Message); 
     } 
    } 

첫 번째 내 등록 된 사용자는 "관리자"가된다. 비록 "userManager.AddToRole (user.Id,"User ");" 등록 된 사용자가 그 역할에 배정되지 않았다는 예외는 발생하지 않습니다. (표를 확인하고 권한 부여 (역할 ...) 여기에 무엇이 잘못되었는지 알 수 없습니다.

답변

0

나는 그것을 계산했습니다. 사용자 이름에 "+"가 붙은 일반 이메일 주소 (예 : [email protected])를 사용했습니다. 등록하는 동안 문제가 발생하지 않으며 AddRoleTo 메소드를 사용하려고 시도 할 때 예외가 발생하지 않지만 AddRoleTo 결과 스택에 사용자 이름에 문자와 숫자 만 허용되는 오류가 나타납니다.