如何登录哪个操作方法是在在的WebAPI控制器执行 [英] How to log which action method is executed in a controller in webapi
问题描述
在的WebAPI,反正是有记录的操作方法的名称为被调用执行或使用动作过滤器。我使用的RouteData属性,如下图所示,但动作值不包含任何值。有什么办法,我可以得到在过滤器动作的名称。
公共类LogActionFilter:ActionFilterAttribute
{
公共覆盖无效OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
日志(actionExecutedContext.ActionContext.RequestContext.RouteData); base.OnActionExecuted(actionExecutedContext);
} 私人无效日志(System.Web.Http.Routing.IHttpRouteData httpRouteData)
{
VAR controllerName = httpRouteData.Values [控制器]; VAR actionName = httpRouteData.Values [行动]; VAR消息=的String.Format(控制器:{0},动作:{1},controllerName,actionName); 的Debug.WriteLine(消息,行动过滤日志);
}
}
您可以找到 actionExecutedContext.ActionContext.ActionDescriptor.ActionName
属性(String)操作名称。
您也可以施放该 ActionDescriptor
到 ReflectedHttpActionDescriptor
并获得的MethodInfo实例
这是所谓的,如果你需要的不仅仅是字符串名称的更多信息。
VAR reflectedActionDescriptor = actionExecutedContext.ActionContext.ActionDescriptor
作为ReflectedHttpActionDescriptor;
//这里检查reflectedActionDescriptor.MethodInfo
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
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
这篇关于如何登录哪个操作方法是在在的WebAPI控制器执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!