1

Here's a filter that I have:

public class ABCFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            set();
            base.OnActionExecuting(actionContext);
        }
    }

Here's my base controller that controllers inherit from:

public class BaseController : ApiController
{
    public int abcd { get; private set; }

    public void set()
    {
        abcd = 123;
    }

I would like to call the function set() that's in the base controller. Is that possible and how could I do it?

Alan2
  • 23,493
  • 79
  • 256
  • 450

1 Answers1

2

You can try:

public class ABCFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            (actionContext.ControllerContext.Controller as BaseController).set(); //Retrieve the current controller from the context.
            base.OnActionExecuting(actionContext);
        }
    }

But it's not recommended because action filters are designed to deal with cross-cutting concerns: Cross cutting concern example

Using it like this couples the filter with specific controllers and cannot be reused for other controllers that are not derived from your BaseController

With your code, I think you can just implement the initialization logic inside BaseController constructor.

public class BaseController : ApiController
{
    public int abcd { get; private set; }
    public BaseController()
    {
        set();
    }
    public void set()
    {
        abcd = 123;
    }
Community
  • 1
  • 1
Khanh TO
  • 48,509
  • 13
  • 99
  • 115
  • I would like to implement in the base constructor but the code needs access to the HttpActionContext and from what I understand (might be wrong) it's not available in the base constructor. – Alan2 Mar 12 '16 at 03:48
  • 1
    @Alan: If that's the case, it's fine to define a filter used `only for BaseController`, but I don't really understand why you need this filter because you can access these context information in your action method. – Khanh TO Mar 12 '16 at 03:54
  • Just wanting to keep the method looking clean. Actually based on what you said I already have an auth filter and I put a call to set() in there. Thanks for ur help. – Alan2 Mar 12 '16 at 04:02