How to log which action method is executed in a co

2019-06-17 05:55发布

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");
    }
}

1条回答
女痞
2楼-- · 2019-06-17 06:20

You can find the action name in the actionExecutedContext.ActionContext.ActionDescriptor.ActionName property (string).

You can also cast that ActionDescriptor to ReflectedHttpActionDescriptor and obtain an instance of the MethodInfo that was called, if you need more information than just string name.

 var reflectedActionDescriptor = actionExecutedContext.ActionContext.ActionDescriptor 
       as ReflectedHttpActionDescriptor;
 //inspect reflectedActionDescriptor.MethodInfo here 
查看更多
登录 后发表回答