Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check AllowAnonymousAttribute in Web API

System.Web.Mvc.ActionDescriptor has method IsDefined which helps to determine whether one or more instances of the specified attribute type are defined for this member.

System.Web.Http.Controllers.HttpActionDescriptor does not have this method.

How can I check AllowAnonymousAttribute using HttpActionDescriptor?

like image 973
FireShock Avatar asked Jul 16 '14 10:07

FireShock


2 Answers

I found. I can use GetCustomAttributes method. For example (from AuthorizeAttribute implementation):

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;
}
like image 96
FireShock Avatar answered Sep 24 '22 20:09

FireShock


The answer by @FireShock is correct, here is a version that I think is easier to read:

private static bool ShouldSkipAuthorization(HttpActionContext actionContext)
{
    return 
        actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>(true).Any() ||
        actionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>(true).Any();
}
like image 24
Marcos Dimitrio Avatar answered Sep 22 '22 20:09

Marcos Dimitrio