Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access a property from an ActionFilterAttribute in my ApiController?

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.

like image 925
Adam Modlin Avatar asked Aug 14 '14 14:08

Adam Modlin


People also ask

What is an ActionFilter?

Action filters are used to implement the logic that get executed before or after a controller action executes. Authorization Filters. It is used to implement authorization and authentication for action filters. Result Filters. Result filters contains logic that gets executed before or after a view result gets executed.

What is ActionFilterAttribute in MVC?

The ActionFilterAttribute is the base class for all the attribute filters. It provides the following methods to execute a specific logic after and before controller action's execution: OnActionExecuting(ActionExecutingContext filterContext): Just before the action method is called.

Which action filter triggers first?

For example, the Authorize filter is an example of an Authorization filter. Action Filter is an attribute that you can apply to a controller action or an entire controller. This filter will be called before and after the action starts executing and after the action has executed.

What are action filters in MVC explain with example?

Action filters are generally used to apply cross-cutting concerns such as logging, caching, authorization, etc. The following example demonstrates creating a custom action filter class for logging. Above, the Log class derived the ActionFilterAttribute class.


1 Answers

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;
    }
}
like image 173
Adam Modlin Avatar answered Oct 22 '22 02:10

Adam Modlin