正如馬修所說,建立一個委託人並在恰當的時機設置它是利用所有基於角色的好東西(如SiteMap)的最簡單方法。
但是有一個比MSDN顯示更容易實現這個標準的方法。
這是我如何實現一個簡單的角色提供
的Global.asax
using System;
using System.Collections.Specialized;
using System.Security.Principal;
using System.Threading;
using System.Web;
using System.Web.Security;
namespace SimpleRoles
{
public class Global : HttpApplication
{
private static readonly NameValueCollection Roles =
new NameValueCollection(StringComparer.InvariantCultureIgnoreCase)
{
{"administrator", "admins"},
// note, a user can be in more than one role
{"administrator", "codePoets"},
};
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
HttpCookie cookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie != null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
Context.User = Thread.CurrentPrincipal =
new GenericPrincipal(Context.User.Identity, Roles.GetValues(ticket.Name));
}
}
}
}
要手動檢查用戶在頁面代碼隱藏的背景:
if (User.IsInRole("admins"))
{
// allow something
}
別處先手用戶關閉當前上下文
if (HttpContext.Current.User.IsInRole("admins"))
{
// allow something
}