正如马修所说,建立一个委托人并在恰当的时机设置它是利用所有基于角色的好东西(如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
}