2014-01-30 19 views
0
[Authorize(Roles="ABC")] 
public class HelloController : Controller 
{ 
    // 
    // GET: /Hello/ 
    public ActionResult Index() 
    { 
     return View(); 
    } 
} 

這裏,具有「ABC」角色的用戶可以訪問Hellocontroller。 我的問題是什麼MVC將比較角色類型「ABC」?MVC中的角色比較

+0

如果您使用的是簡單成員資格,則會將此字符串與所有授權給已認證用戶的角色進行比較。 – Fals

+0

var role = System.Web.Security.Roles.GetRolesForUser();我檢查了分配給授權用戶的角色數量。它讓我產生了null –

+0

閱讀角色授權。這個鏈接(http://www.codeproject.com/Articles/342061/Understanding-ASP-NET-Roles-and-Membership-A-Begin)可能會有所幫助。谷歌瞭解更多信息 - 有很多。 –

回答

1

角色被添加到HttpContext的IPrincipal。您可以創建一個GenericPrincipal,在構造函數中解析角色列表並將其設置爲HttpContext.User。隨後的GenericPrincipal將通過User.IsInRole("role")可以訪問或[Authorize(Roles="role")]屬性

這樣做(在C#)的一種方法是創建身份驗證票證時添加您的角色在用戶數據參數,以逗號分隔字符串

string roles = "Admin,Member"; 
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
    1, 
    userId, //user id 
    DateTime.Now, 
    DateTime.Now.AddMinutes(20), // expiry 
    false, //do not remember 
    roles, 
    "/"); 
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, 
            FormsAuthentication.Encrypt(authTicket)); 
Response.Cookies.Add(cookie); 

然後從身份驗證票證從你的Global.asax.cs從@大衛格倫

01進入角色列表,並創建一個的GenericPrincipal

protected void Application_AuthenticateRequest(Object sender, EventArgs e) { 
    HttpCookie authCookie = 
       Context.Request.Cookies[FormsAuthentication.FormsCookieName]; 
    if (authCookie != null) { 
     FormsAuthenticationTicket authTicket = 
            FormsAuthentication.Decrypt(authCookie.Value); 
     string[] roles = authTicket.UserData.Split(new Char[] { ',' }); 
     GenericPrincipal userPrincipal = 
         new GenericPrincipal(new GenericIdentity(authTicket.Name), 
              roles); 
     Context.User = userPrincipal; 
    } 
    } 
} 

報價