5

I have a custom ActionFilterAttribute. For the sake of this question let's assume it's as follows:

public class CustomActionFilterAttribute : ActionFilterAttribute {
    public bool success { get; private set };

    public override void OnActionExecuting(HttpActionContext actionContext) {
        //Do something and set success
        success = DoSomething(actionContext);
    }
}

My controller is then decorated with CustomActionFilter. What I am looking for is a way (in my controller method) to do something like:

[CustomActionFilter]
public class MyController : ApiController {
    public ActionResult MyAction() {
        //How do I get the 'success' from my attribute?
    }
}

If there is a more accepted way of doing this please let me know.

Adam Modlin
  • 2,994
  • 2
  • 22
  • 39
  • duplicate of [How do you Read the value of an attribute in a Method](http://stackoverflow.com/questions/2493143/how-do-you-read-the-value-of-an-attribute-in-a-method) – Justin Helgerson Aug 14 '14 at 14:35
  • Unfortunately this will not work for me because my attribute is not on the action but on the controller. – Adam Modlin Aug 14 '14 at 16:26
  • 1
    Would this one work for you? http://stackoverflow.com/questions/2656189/how-do-i-read-an-attribute-on-a-class-at-runtime – Justin Helgerson Aug 14 '14 at 16:34
  • I suppose that could possibly work but I was able to solve it in my answer below before I saw your response. – Adam Modlin Aug 14 '14 at 17:09

1 Answers1

6

I discovered I could do the following to satisfy my problem:

[CustomActionFilter]
public class MyController : ApiController {
    public ActionResult MyAction() {
        var myAttribute = ControllerContext
                          .ControllerDescriptor
                          .GetCustomAttributes<CustomActionFilter>()
                          .Single();
        var success = myAttribute.success;
    }
}
Adam Modlin
  • 2,994
  • 2
  • 22
  • 39