Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
   }
}
like image 713
Kristina Koysina Avatar asked May 03 '26 17:05

Kristina Koysina


2 Answers

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).

like image 163
kiziu Avatar answered May 06 '26 06:05

kiziu


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 
    }
});
like image 32
ubi Avatar answered May 06 '26 07:05

ubi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!