Currently I have:
public enum ApplicationRoles
{
Undefined = 0,
Basic = 1,
Admin = 2
}
// within a method:
bool? isAuthorized = null;
string[] allowedRoles = { "Admin" };
List<ApplicationRoles> userRoles = new List<ApplicationRoles>();
userRoles.Add(ApplicationRoles.Admin);
foreach (string role in allowedRoles)
{
foreach (ApplicationRoles appRole in userRoles)
{
if (appRole != ApplicationRoles.Undefined)
isAuthorized = role.ToLower() == appRole.ToString().ToLower();
}
if ((bool)isAuthorized)
break;
}
isAuthorized would return true in this example.
How can this be converted to a Linq statement?
You are looking for Any
method:
allowedRoles
.Any(role => user.Roles.Any(r => r != ApplicationRoles.Undefined &&
role.ToLower() == r.ToString().ToLower()));
If you wanna check only for one role there is no need for allowedRoles
array:
user.Roles.Any(r => r.ToLower() == "admin");
You shouldn't store any of your values as hardcoded strings; that's what the enums are for, after all.
var allowedRoles = new HashSet<ApplicationRoles> { ApplicationRoles.Admin };
bool isAuthorized = userRoles.Any(r => allowedRoles.Contains(r));
This approach also works fine with arrays.
var allowedRoles = new[] { ApplicationRoles.Admin };
var userRoles = new[] { ApplicationRoles.Basic };
bool isAuthorized = userRoles.Any(r => allowedRoles.Contains(r));
What about
var allowedRoles = Enum.GetValues(typeof(ApplicationRoles))
.Cast<ApplicationRoles>()
.Except(ApplicationRoles.Undefinied); // allow all except undefined
bool isAuthorized = userRoles.Any(r => allowedRoles.Contains(r));
this way you don't need to mess with any string comparison.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.