2016-03-31 49 views
1

我正在使用VS 2013並正在開發MVC Web應用程序。它使用Windows身份驗證。我寫了一個bool方法來檢查特定AD組中的用戶。如何隱藏不屬於AD組的用戶的鏈接

string user = User.Identity.Name; 
PrincipalContext context = new PrincipalContext(ContextType.Domain, "DOMAINNAME"); 
if(user.IsMemberOf(ctx, IdentityType.SamAccountName, "GroupName")){ 
    return true; 
} 
else 
return false; 

但是,我不能從我的視圖使用此方法,因爲它不是擴展方法。

我想要做的是,檢查用戶是否在組中,然後隱藏特定鏈接(如果他/她不在該組中)。

有什麼建議嗎?

回答

1

爲什麼不能有一個屬性在你的模型:

public bool IsAuthorized { get; set; } 

在控制器中,設置在動作方法的財產返回模型前:在視圖

YourModel model = ... 

string user = User.Identity.Name; 
PrincipalContext context = new PrincipalContext(ContextType.Domain, "DOMAINNAME"); 
model.IsAuthorized = user.IsMemberOf(ctx, IdentityType.SamAccountName, "GroupName"); 

return View(model); 

然後,只需隱藏鏈接如果沒有授權

@if (model.IsAuthorized) 
{ 
    @Html.Action(...) // or whatever your link is 
}