What you need is action filters. You can apply action filters directly to controllers as attributes, the caveat with Action filters is that at this point the controller route is already known but you can still control (very much like AOP) if the action method can be executed or not:
ASP.NET Web API ActionFilter example
Look at how you can use an action filter, in this case for logging:
public class LogActionFilter : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
Log(actionExecutedContext.ActionContext.RequestContext.RouteData);
base.OnActionExecuted(actionExecutedContext);
}
private void Log(System.Web.Http.Routing.IHttpRouteData httpRouteData)
{
var controllerName = "controller name";
var actionName = "action name";
var message = String.Format("controller:{0}, action:{1}", controllerName, actionName);
Debug.WriteLine(message, "Action Filter Log");
}
}
How to log which action method is executed in a controller in webapi
You can also use message handlers, which are executed before the controller is resolved:
HTTP Message Handlers in ASP.NET Web API
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…