System.Web.Mvc.ActionDescriptor具有方法IsDefined這有助於確定是否指定的屬性類型中的一個或多個實例對本構件限定。檢查AllowAnonymousAttribute在網頁API
System.Web.Http.Controllers.HttpActionDescriptor沒有此方法。
我該如何檢查AllowAnonymousAttribute使用HttpActionDescriptor?
System.Web.Mvc.ActionDescriptor具有方法IsDefined這有助於確定是否指定的屬性類型中的一個或多個實例對本構件限定。檢查AllowAnonymousAttribute在網頁API
System.Web.Http.Controllers.HttpActionDescriptor沒有此方法。
我該如何檢查AllowAnonymousAttribute使用HttpActionDescriptor?
我找到了。我可以使用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;
}
通過@FireShock的答案是正確的,這裏是我認爲是更容易閱讀版本:
private static bool ShouldSkipAuthorization(HttpActionContext actionContext)
{
return
actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>(true).Any() ||
actionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>(true).Any();
}