How to register which action method is executed in the controller in webapi

In WebAPI, you still need to register the name of the action method for the controller that is called or executed using the action filter. I use the RouteData property as shown below, but the action value does not contain any value. Is there a way to get the name of an action in a 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"); } } 
+6
source share
1 answer

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

You can also do this ActionDescriptor before the ReflectedHttpActionDescriptor and get an instance of MethodInfo that was called if you need more information than just a string name.

  var reflectedActionDescriptor = actionExecutedContext.ActionContext.ActionDescriptor as ReflectedHttpActionDescriptor; //inspect reflectedActionDescriptor.MethodInfo here 
+2
source

Source: https://habr.com/ru/post/977115/


All Articles