'WebApi AuthorizationFilterAttribute: ActionArguments are empty

I'm implementing an AuthorizationFilterAttribute for a WebApi controller, but I don't seem to have access to the parameters that are being passed into the controller:

In MVC4, this works fine:

public class MyMVCController : Controller
{
    [CanAccessMyResourceApi]
    public MyViewModel Get(int id)
    {
       //...
    }
}

public class CanAccessMyResourceMVCAttribute : CanAccessAttributeBase
{
   public override void OnAuthorization(AuthorizationContext filterContext)
   {
       var param = filterContext.Controller.ValueProvider.GetValue("id")
       /// ... 
   }
}

But in WebAPI, I think the parameter should be in the ActionArguments, but "param" here is empty:

public class MyWebApiController : ApiController
{
   [CanAccessMyResourceWebApi]
   public MyViewModel Get(int id)
   {
      //...
   }

}

public class CanAccessMyResourceWebApiAttribute : AuthorizationFilterAttribute 
{
    public override void OnAuthorization(HttpActionContext filterContext)
    {       
        // the debugger shows that ActionArguments is empty:
        var param = filterContext.ActionArguments["id"]
        /// ...
    }
}

Is the parameter that's being passed into the controller available somewhere else? (I verified that the controller's action is getting the Id value correctly when I remove the filter attribute.)



Solution 1:[1]

Have you taken a look at the solutions from this StackOverflow page?

Specifically:

var variable = HttpContext.Current.Request.Params["parameterName"];

public class CustomAuthorizeAttribute : AuthorizeAttribute
  {
     protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
     {
        var clientId = actionContext.ControllerContext.RouteData.Values["clientid"];

     }
  }

Hope this helped!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sergio Carneiro