Search code examples
c#apiactionfilterattribute

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


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
   }
}

Solution

  • To access the collection of parameters of currently executed method, you invoke

    actionContext.ActionDescriptor.GetParameters()
    

    You can that iterate through the collection of HttpParameterDescriptor and find the parameter you need. You can do it by name, index or whatever means you find appropriate.

    Then, you can use method GetCustomAttributes<TClass>() defined in object of type HttpParameterDescriptor to check if the parameter is marked with attribute of type TClass. If you need an instance of the attribute to check the value, simply get it from the resulting collection of attributes (if found).