That check environment should be an ActionFilterAttribute
:
public class CheckEnvironmentFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
// Use the "as" cast to don't throw an invalid cast exception
// if this attribute is applied to the wrong controller...
ServiceController serviceController =
actionContext.ControllerContext.Controller as ServiceController;
if(serviceController != null)
{
serviceController.IsDebugging = true;
}
}
}
Now add the whole filter attribute as regular C# attribute to your ServiceController
:
[CheckEnvironmentFilter]
public class ServiceController : ApiController
...
...and the so-called filter method will be hit before any action has been executed from the whole API controller.
BTW, I would design an interface IDebuggable
as follows:
public interface IDebuggable
{
bool IsDebugging { get; set; }
}
...and I would implement it on any controller that might require the whole action filter to work:
[CheckEnvironmentFilter]
public class ServiceController : ApiController, IDebuggable
{
public bool IsDebugging { get; set; }
}
...and finally I would refactor the so-called filter to cast controllers to IDebuggable
:
public class CheckEnvironmentFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
// Use the "as" cast to don't throw an invalid cast exception
// if this attribute is applied to the wrong controller...
IDebuggable debuggableController =
actionContext.ControllerContext.Controller as IDebuggable;
if(debuggableController != null)
{
debuggableController.IsDebugging = true;
}
}
}
This is better than #1 approach, because now the CheckEnvironmentFilterAttribute
will support any controller which implements IDebuggable
.