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");
}
}
Default Action Methods In Web API, Get, Post, Put, and Delete verbs are used as corresponding action methods- Get(), Post ([FromBody]string value), Put (int id, [FromBody]string value), Delete (int id) for manipulating data like get, insert, update and delete.
So, if you want to return a View you need to use the simple ol' Controller . The WebApi "way" is like a webservice where you exchange data with another service (returning JSON or XML to that service, not a View). So whenever you want to return a webpage ( View ) for a user you don't use the Web API.
An action filter is an attribute that you can apply to a controller action -- or an entire controller -- that modifies the way in which the action is executed.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With