Fir*_*ock 4 c# security authentication asp.net-web-api
System.Web.Mvc.ActionDescriptor具有方法IsDefined,该方法有助于确定是否为此成员定义了指定属性类型的一个或多个实例。
System.Web.Http.Controllers.HttpActionDescriptor没有此方法。
如何使用HttpActionDescriptor 检查AllowAnonymousAttribute?
我发现。我可以使用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;
}
Run Code Online (Sandbox Code Playgroud)
@FireShock 的答案是正确的,这是一个我认为更容易阅读的版本:
private static bool ShouldSkipAuthorization(HttpActionContext actionContext)
{
return
actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>(true).Any() ||
actionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>(true).Any();
}
Run Code Online (Sandbox Code Playgroud)