How to log which action method is executed in a controller in webapi

。_饼干妹妹 提交于 2020-01-03 08:45:22

问题


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:


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 


来源:https://stackoverflow.com/questions/26523290/how-to-log-which-action-method-is-executed-in-a-controller-in-webapi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!