How can I read parameter attribute value in web api action filter

Kristina Koysina picture Kristina Koysina · Sep 15, 2016 · Viewed 9.7k times · Source

I've got an API method where the Id parameter is annotated with CacheType attribute

public Object Get([CacheType(CacheTypes.Venue)]int Id)
{
            ....
}

Can I read the value of the parameter attribute inside of ActionFilterAttribute

public class CacheOutputAttribute : ActionFilterAttribute
{
   public override void OnActionExecuting(HttpActionContext actionContext)
   {
        //read CacheType value
   }
}

Answer

ubi picture ubi · Sep 15, 2016

To get the parameter value

actionContext.ActionArguments["id"]

To do something with the parameters that have CacheOutput attribute

actionContext.ActionDescriptor.GetParameters().ToList().ForEach(p =>
{
    var cacheOutput = p.GetCustomAttributes<CacheOutputAttribute>();
    if (cacheOutput.Any())
    {
        // do something 
    }
});