2016-10-03 33 views
0

我第一次使用會員和角色提供者爲我的登錄頁面。我的會員資格工作正常,但我無法在登錄頁面上使用角色提供者。 我有一個名爲MyAccount控制器的控制器。該控制器將驗證用戶成員資格,並在驗證後將根據用戶角色重定向到Home控制器。 這裏是如何在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(); 
    } 

我一個米不知道我應該檢查用戶角色,在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")) 
相關問題