是的,你可以这样做。
Authorize 使用 IPrincipal 的 IsInRole 方法来确定用户是否属于给定角色。
您可以在 Global.asax 中的 AuthenticateRequest 事件期间切换 IPrincipal 的默认实现,并使用您的实现方式来处理它。
以下是一些示例代码,它们可能实际上可以工作和编译,并且不会让您的网站受到黑客的攻击:
private void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (!Request.IsAuthenticated)
{
Context.User = new MyPrincipal { Identity = new MyIdentity
{ Type = UserType.Inactive, Id = int.MinValue }};
Thread.CurrentPrincipal = Context.User;
}
else
{
HttpCookie authCookie = Request.Cookies[
FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket =
FormsAuthentication.Decrypt(authCookie.Value);
var identity = Db.GetIdentity(
authTicket.Name, new HttpRequestWrapper(Request));
Context.User = new MyPrincipal { Identity = new MyIdentity
{ Type = UserType.Inactive, Id = int.MinValue }};
Thread.CurrentPrincipal = Context.User;
}
}
}