一種方法是重寫您的aspx表單的OnLoad,並檢查經過身份驗證的用戶是否被允許根據角色訪問資源。所以,你創建例如BasePage.cs(其中你定義一個類的BasePage它繼承自System.Web.UI.Page)從所有窗體(ASPX)繼承,在你這樣做:
protected override void OnLoad(EventArgs e)
{
InitializeSitemap();
if (SiteMap.CurrentNode != null)
{
if (!UrlHelper.IsAnonymousAllowed(SiteMap.CurrentNode) && (!HttpContext.Current.User.Identity.IsAuthenticated || !UrlHelper.IsAccesible(SiteMap.CurrentNode)))
{
// You can redirect here to some form that has a custom message
Response.Redirect("~/Forms/Logout.aspx");
return;
}
}
base.OnLoad(e);
}
然後在您的UrlHelper類,你需要的是上面使用IsAccessible功能:
public static bool IsAccesible(SiteMapNode node)
{
bool toRole = false;
foreach (string role in node.Roles)
{
if (role == "*" || HttpContext.Current.User.IsInRole(role))
{
toRole = true;
}
}
return toRole;
}
下面是IsAnonymousAllowed如果你想知道:
public static bool IsAnonymousAllowed(SiteMapNode node)
{
return node[AllowAnonymousAttribute] != null ? bool.Parse(node[AllowAnonymousAttribute]) : false;
}
我如何知道他不能訪問該頁面? 我可以確定他在哪個角色,但不能訪問請求的頁面。 – user9659 2009-06-26 11:01:35
那麼你應該做出像關卡一樣的東西。如果你有4級以上,你可以訪問該頁面。或者對於角色,您應該在每個頁面上指定一個可以訪問該頁面的特定角色。 – Timotei 2009-06-26 11:53:55