【发布时间】:2012-06-05 08:32:26
【问题描述】:
我有两个属性:
public class AnonymousAllowedAttribute : AuthorizeAttribute { }
public class ActionAuthorizeAttribute : AuthorizeAttribute {
public override void OnAuthorization(AuthorizationContext filterContext) {
bool skipAuthorization =
filterContext.ActionDescriptor.IsDefined(typeof(AnonymousAllowedAttribute), true)
||
filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AnonymousAllowedAttribute), true);
if(!skipAuthorization)
base.OnAuthorization(filterContext);
}
bool CustomeCheck() {
bool result = //My Checks
return result;
}
}
我将ActionAuthorizeAttribute 定义为全局属性。
所以我需要这 3 件物品:
1- 如果没有登录 (!User.Identity.IsAuthenticated):转到登录页面 Accounts/LogIn。
我必须提到标有AnonymousAllowedAttribute 的LogIn 操作。
2- 如果登录 (User.Identity.IsAuthenticated) 并且操作或控制器具有AnonymousAllowedAttribute,则授权为真(不需要任何授权)。
3- 如果登录 (User.Identity.IsAuthenticated) 并且操作还没有 AnonymousAllowedAttribute 返回 CustomeCheck() 方法
如您所见,我通过覆盖 OnAuthorization() 方法尝试第二个。
第三个如下:
protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext){
if(!httpContext.User.Identity.IsAuthenticated)
return false;
return CustomeCheck();
}
但是当我没有登录时总是返回:
IIS 7.5 错误详情:
HTTP 错误 401.0 - 未经授权
使用此网址:http://myProject/Accounts/LogIn?ReturnUrl=%2f
问题出在哪里?如何实现ActionAuthorizeAttribute来实现这3个目标?
更新
我找到答案:问题是:AnonymousAllowedAttribute 需要继承自 Attribute 而不是 AuthorizeAttribute。
【问题讨论】:
标签: asp.net-mvc asp.net-mvc-3 authorization action-filter authorize-attribute