[英]How can I check if a user is in any one of a few different roles with MVC4 Simple membership?
我知道檢查用戶是否處於角色的一種好方法是:
if (User.IsInRole("Admin"))
{
}
但是,如何檢查我的用戶是否屬於“作者”、“管理員”或“超級”角色之一? 有沒有辦法在不為每個角色編碼“User.IsInRole”的情況下做到這一點?
沒有內置的方法來檢查用戶是否具有多個角色,但是創建一個很好的擴展方法來為您處理它是非常簡單的:
public static bool IsInAnyRole(this IPrincipal principal, params string[] roles)
{
return roles.Any(principal.IsInRole);
}
用法是:
if (User.IsInAnyRole("Admin", "Author", "SuperUser"))
{
}
編輯:不編碼每個角色,做一個 LINQ 擴展方法,像這樣:
private static bool IsInAnyRole(this IPrincipal user, List<string> roles)
{
var userRoles = Roles.GetRolesForUser(user.Identity.Name);
return userRoles.Any(u => roles.Contains(u));
}
對於使用,請執行以下操作:
var roles = new List<string> { "Admin", "Author", "Super" };
if (user.IsInAnyRole(roles))
{
//do something
}
或者沒有擴展方法:
var roles = new List<string> { "Admin", "Author", "Super" };
var userRoles = Roles.GetRolesForUser(User.Identity.Name);
if (userRoles.Any(u => roles.Contains(u))
{
//do something
}
你也可以使用
if(Roles.GetRolesForUser(model.UserName).Contains("Admin")){
}
我想詳細說明 mattytommo 的答案,這是我使用的:
擴展方法:
public static bool IsInAnyRole(this IPrincipal user, string[] roles)
{
//Check if authenticated first (optional)
if (!user.Identity.IsAuthenticated) return false;
var userRoles = Roles.GetRolesForUser(user.Identity.Name);
return userRoles.Any(roles.Contains);
}
常數:
public static class Role
{
public const string Administrator = "Administrator";
public const string Moderator = "Moderator";
}
用法:
if (User.IsInAnyRole(new [] {Role.Administrator,Role.Moderator}))
{
//Do stuff
}
我使用了下面的代碼。 就我而言,我有一個以分號分隔的字符串作為從 web.config 讀取的參數。 如果您要傳遞列表,則可以輕松更改以下代碼。
public class ActiveDirectoryGroup
{
public static bool IsInAnyRole(string adRoles)
{
return adRoles.Split(Convert.ToChar(";")).Any(role => !string.IsNullOrEmpty(role.Trim()) && HttpContext.Current.User.IsInRole(role.Trim()));
//If list is passed use below
//return listParameter.Any(role => !string.IsNullOrEmpty(role.Trim()) && HttpContext.Current.User.IsInRole(role.Trim()));
}
}
在 web.config 中:
<appSettings>
<add key="ADGroup" value="Domain\Admin;Domain\Supervisor;Domain\Manager;" />
</appSettings>
我在頁面加載中使用它如下:
if (ActiveDirectoryGroup.IsInAnyRole(ConfigurationManager.AppSettings["ADGroup"]))
{
//do something
}
請使用這個簡單的方法:
@using Microsoft.AspNet.Identity
@if (Request.IsAuthenticated)
{
if (User.IsInRole("Administrator") || User.IsInRole("Moderator"))
{
... Your code here
}
}
就我而言,我每個用戶只有一個角色。 所以我是這樣做的:
if (User.Roles.FirstOrDefault().RoleId == "7b433246-5881-4ace-bbaa-e5514191171c") {
//Do something
}
那這個呢?
if (User.Roles.Count() != 0)
{
//User is not in any role
}else
{
//User is in at least one role
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.