我创建了一个自定义授权,当某个操作有[Authorize]
时忽略:
public class MyGlobalAuthorizeAttribute: AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
// check if action is decorated with an Authorize...
var action = filterContext.ActionDescriptor
if (action.IsDefined(typeof(AuthorizeAttribute), true))
return;
base.OnAuthorization(filterContext);
}
}
...然后我在全局过滤器中配置它,默认只允许管理员:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new MyGlobalAuthorizeAttribute() { Roles = "Admin" });
}
}
如果我装饰这样的动作:
public class MyController: Controller
{
[Authorize] // non-admins can access this action..
public ActionResult Index()
{
}
}
......它运作正常。但是,如果我将[Authorize]
置于控制器中,则MyGlobalAuthorizeAttribute
无法检测到它。
我找到了许多覆盖的例子,但所有这些都是关于操作覆盖控制器或全局授权,但不是控制器覆盖全局授权。
有可能实现这个目标吗?
答案 0 :(得分:3)
您还需要检查ControllerDescriptor:
var action = filterContext.ActionDescriptor;
if (action.IsDefined(typeof(AuthorizeAttribute), true))
return;
if (action.ControllerDescriptor.IsDefined(typeof(AuthorizeAttribute), true))
return;