【问题标题】:Check AllowAnonymousAttribute in Web API检查 Web API 中的 AllowAnonymousAttribute
【发布时间】:2014-09-06 20:57:48
【问题描述】:
System.Web.Mvc.ActionDescriptor 具有 IsDefined 方法,该方法有助于确定是否为此成员定义了指定属性类型的一个或多个实例。
System.Web.Http.Controllers.HttpActionDescriptor没有这个方法。
如何使用 HttpActionDescriptor 检查 AllowAnonymousAttribute?
【问题讨论】:
标签:
c#
security
authentication
asp.net-web-api
【解决方案1】:
我找到了。我可以使用 GetCustomAttributes 方法。例如(来自 AuthorizeAttribute 实现):
private static bool SkipAuthorization(HttpActionContext actionContext)
{
if (!Enumerable.Any<AllowAnonymousAttribute>((IEnumerable<AllowAnonymousAttribute>) actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>()))
return Enumerable.Any<AllowAnonymousAttribute>((IEnumerable<AllowAnonymousAttribute>) actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>());
else
return true;
}
【解决方案2】:
@FireShock 的回答是正确的,这是我认为更容易阅读的版本:
private static bool ShouldSkipAuthorization(HttpActionContext actionContext)
{
return
actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>(true).Any() ||
actionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>(true).Any();
}