2016-10-03 3 views
0

로그인 페이지에 멤버쉽 및 역할 공급자를 처음 사용합니다. 내 멤버쉽은 정상적으로 작동했지만 로그인 페이지에서 역할 공급자를 사용할 수 없었습니다. MyAccount 컨트롤러라는 컨트롤러가 하나 있습니다. 이 컨트롤러는 사용자 멤버십을 확인한 후 사용자 역할에 따라 홈 컨트롤러로 리디렉션됩니다.MVC 5에서 역할 공급자를 사용하는 방법은 무엇입니까?

[HttpPost] 
    [ValidateAntiForgeryToken] 
    public ActionResult Login(Login l, string returnUrl = "") 
    {if (ModelState.IsValid) 
     { 
      var isValidUser = Membership.ValidateUser(l.UserName, l.Password); 
      if (isValidUser) 
      { 
       FormsAuthentication.SetAuthCookie(l.UserName, l.RememberMe); 
       if (Url.IsLocalUrl(returnUrl)) 
       { 
        return Redirect(returnUrl); 
       } 

       else If(*"USER ROLE AS ADMIN"*) 
       { 
        RedirectToAction("AdminIndex","Home"); 
       } 
       else 
       { 
        RedirectToAction("ClientIndex","Home"); 
       } 

      } 
     } 
     ViewBag.ErrorMassage = "Wrong Id or Password"; 
     ModelState.Remove("Password"); 
     return View(); 
    } 

그리고

홈 컨트롤러 : 여기

내 계정 컨트롤러

[Authorize (Roles= "Admin")] 
    public ActionResult AdminIndex() 
    { 
     return View(); 
    } 

    [Authorize (Roles = "Client")] 
    public ActionResult ClientIndex() 
    { 
     return View(); 
    } 

I 확실하지 않습니다 어디에서 사용자 역할, MyAccount 컨트롤러 또는 홈 컨트롤러를 확인해야합니까?

RoleProvider :

public override string[] GetRolesForUser(string username) 
    { 
     if (!HttpContext.Current.User.Identity.IsAuthenticated) 
     { 
      return null; 
     } 

     //check cache 
     var cacheKey = string.Format("{0}_role", username); 
     if (HttpRuntime.Cache[cacheKey] != null) 
     { 
      return (string[])HttpRuntime.Cache[cacheKey]; 
     } 
     string[] roles = new string[] { }; 
     roles = gateway.GetUserRole(username); 
     { 

      if (roles.Any()) 
      { 
       HttpRuntime.Cache.Insert(cacheKey, roles, null, DateTime.Now.AddMinutes(_cacheTimeoutInMinute), Cache.NoSlidingExpiration); 

      } 
     } 
     return roles; 
    } 
public override bool IsUserInRole(string username, string roleName) 
    { 
     var userRoles = GetRolesForUser(username); 
     return userRoles.Contains(roleName); 
    } 

가 어떻게 내 컨트롤러에이 RoleProvider를 사용하고 관리자 또는 클라이언트 작업을 리디렉션 할 수 있습니다?

답변

0

등록 web.config에서 사용자 정의 역할 공급자 :

<roleManager defaultProvider="DefaultRoleProvider"> 
    <providers> 
     <add name="DefaultRoleProvider" type="MyNamespace.MyRoleProvider, MyAssembly" /> 
    </providers> 
</roleManager> 

업데이트 MyAccount 컨트롤러 Login 액션 메소드 :

if (Roles.IsUserInRole("Admin")) 
관련 문제