3

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
   }
}
2
  • have you tied anything yourself or are you just copying code from the net and asking us to do the work for you? Commented Sep 15, 2016 at 11:54
  • It's possible with help of Reflection Commented Sep 15, 2016 at 11:59

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

3

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

1 Comment

Don't the ActionArguments contain only pairs of name/value and not metadata of the method argument?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.