我想弄清楚如何根據用戶角色顯示/隱藏用戶鏈接。我知道如何爲操作方法設置authorize屬性,但是如果用戶在我的角色數據庫中是說,管理員或管理員,則無法在鏈接中顯示隱藏。在ASP.Net MVC視圖中顯示/隱藏鏈接
任何好的文章或代碼示例有人可以指向我?
我想弄清楚如何根據用戶角色顯示/隱藏用戶鏈接。我知道如何爲操作方法設置authorize屬性,但是如果用戶在我的角色數據庫中是說,管理員或管理員,則無法在鏈接中顯示隱藏。在ASP.Net MVC視圖中顯示/隱藏鏈接
任何好的文章或代碼示例有人可以指向我?
在您的意見中,您可以通過System.Web.Mvc.ViewPage
的User
財產來引用IPrincipal
用戶。
E.g.在你看來,你可以有這樣的:
<% if (User.IsInRole("Admin")) { %>
<%= Html.ActionLink("Admin only link", "Edit", "Users") %>
<% } %>
<% if (User.IsInRole("Manager") || User.IsInRole("Admin")) { %>
<%= Html.ActionLink("Manager & Admin only link", "Edit", "Product") %>
<% } %>
HTHS,
查爾斯
這是一兩件事,我真的不喜歡用MVC(如在ASP.Net MVC,不是模式)有一個將UI邏輯轉化爲標記的趨勢。
一旦它在aspx中,就沒有辦法對該邏輯運行單元測試。我個人認爲帶有合適的UI模式(MVC或MVP等)的webforms會比頁面上散佈着無法測試的條件邏輯更合適。
<% if(HttpContext.Current.User.IsInRole("Admin")){%> <a href="/Admin">Admin</a> <% } %>
使用此代碼。這很容易。
我使用一個靜態類進行角色驗證,並在cshtml中使用這個類,角色驗證不在cshtml中。
我有我的授權功能或數據庫中的內容(由用戶或角色),所以如果訪問定義更改,您不必重新部署。
public static class AuthorizeContent
{
public static bool AuthorizeAccessContent(string Content)
{
bool bReturn = false;
DBContext db = new DBContext();
string[] RolesUser = Roles.GetRolesForUser(WebSecurity.CurrentUserName);
foreach (AuthorizedContentRole aut in db.AuthorizedContentRole)
{
foreach (string rol in RolesUser)
{
if (aut.Role==rol && aut.Content==Content)
{
bReturn = true;
break;
}
}
}
foreach (AuthorizedContentUser aut in db.AuthorizedContentUser)
{
if (aut.UserName == WebSecurity.CurrentUserName && aut.Content == Content)
{
bReturn = true;
break;
}
}
return bReturn;
}
///在CSHTML
@if (AuthorizeContent.AuthorizeAccessContent(Content))
{
<li class="two">
<h5>Administrator link</h5>
@Html.ActionLink("Admin secret info","Index", "Information")
</li>
}
你也可以使用像[AccionAuthorize(動作= 「爲myContent」)
public class AccionAuthorizeAttribute : AuthorizeAttribute
{
public string Action { get; set; }
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
filterContext.Result = new HttpUnauthorizedResult();
else if (!AutorizacionContenido.AutorizaAccesoContenido(Action))
filterContext.Result = new HttpUnauthorizedResult();
base.OnAuthorization(filterContext);
}
}
由於過濾器!這裏有一個轉折點 - 我在母版頁中有我的標籤鏈接,我希望爲特定角色顯示一個標籤。你知道我可以如何給IPrincipal的主人添加一個參考嗎? – Ben 2009-12-07 06:54:41
使用'HttpContext.Current.user'或'ViewContext.HttpContext.User' - 應該這樣做:-) – Charlino 2009-12-07 07:03:03
啊,現在我可以繼續前進......感謝幫助! – Ben 2009-12-07 07:10:17