In WebAPI, is there anyway to log the name of the action method for a controller that gets called or executed using an action filter. I am using the RouteData property as shown below, but the action value does not contain any value. Is there any way I can get the action name in the filter.
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 = httpRouteData.Values["controller"];
var actionName = httpRouteData.Values["action"];
var message = String.Format("controller:{0}, action:{1}", controllerName, actionName);
Debug.WriteLine(message, "Action Filter Log");
}
}
You can find the action name in the
actionExecutedContext.ActionContext.ActionDescriptor.ActionName
property (string).You can also cast that
ActionDescriptor
toReflectedHttpActionDescriptor
and obtain an instance of theMethodInfo
that was called, if you need more information than just string name.