【发布时间】:2014-07-16 02:27:14
【问题描述】:
问题:我正在搜索自定义身份对象中的用户角色集合。这些角色有一个连接到它们的部门,因此该角色不仅仅是“角色”,而是具有“部门:角色”的模式。
由于角色是在不知道“部门”部分的对象中定义的,因此在构建授权列表时需要忽略此部分。 实际上,我正在每个“Department:Role”项目中寻找“:Role”。
我正在使用 LINQ 来执行此操作并使其正常工作(发布在下面),但如果可能的话,我想通过删除 foreach 循环来简化它。我已经在网上搜索了几个小时,并尝试了许多不同的解决方案。最接近我想要完成的两个似乎是here 和here。也许答案就在这些里面,我只是不明白。
提前感谢您的帮助/建议。
我的代码:
protected static void AddObjectAuthorizationRules() {
//Code that gets current user context...
string[] pDefinedRoles = new string[] { "Developer", "Admin", "User" };
List<string> _createRoles = ProcessAuthorizationRoles(pDefinedRoles, pIdentity);
//Object authorization code that uses _createRoles...
}
private List<string> ProcessAuthorizationRoles(string[] pDefinedRoles, CustomIdentityClass pIdentity) {
List<string> _allowRoles = new List<string>();
foreach (var _role in pDefinedRoles) {
var partial = string.Format(":{0}", _role);
string[] tmp = (from r in pIdentity.Roles
where r.Contains(partial)
select r).ToArray();
foreach (string found in tmp) {
_allowRoles.Add(found);
}
}
return _allowRoles;
}
【问题讨论】: