Asp.net-Mvc-5

在視圖中使用 User.IsInRole()

  • September 4, 2015

在我的 mvc5 項目中,為未經授權的使用者禁用操作連結,我確實喜歡這樣

@if (User.IsInRole("Admin") | User.IsInRole("Manager"))
{ 
       @Html.ActionLink("Add New Record", "ProductTypeIndex", "ProductType")
} 

但是如果有很多角色需要檢查,那麼這個@if() 就會變得很長。如何避免這種情況?我是否需要為此自定義助手(如果需要,我該如何處理)?幫助表示讚賞..

您可以編寫自己的擴展方法並在程式碼中使用它。

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
} 

雖然您也可以在視圖中使用這些擴展方法,但盡量避免在視圖中編寫應用程序邏輯,因為視圖不容易進行單元測試。

引用自:https://stackoverflow.com/questions/32369229