您可以编写自己的扩展方法并在代码中使用它。
public static class PrincipalExtensions
{
public static bool IsInAllRoles(this IPrincipal principal, params string[] roles)
{
return roles.All(r => principal.IsInRole(r));
}
public static bool IsInAnyRoles(this IPrincipal principal, params string[] roles)
{
return roles.Any(r => principal.IsInRole(r));
}
}
现在你可以简单地调用这个扩展方法:
// user must be assign to all of the roles
if(User.IsInAllRoles("Admin","Manager","YetOtherRole"))
{
// do something
}
// one of the roles sufficient
if(User.IsInAnyRoles("Admin","Manager","YetOtherRole"))
{
// do something
}
虽然您也可以在视图中使用这些扩展方法,但尽量避免在视图中编写应用程序逻辑,因为视图不容易进行单元测试。