Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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");
    }
}
like image 732
user2813261 Avatar asked Oct 23 '14 07:10

user2813261


People also ask

How do you call an action method in Web API?

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.

How can you return to view from the ASP Net Web API method?

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.

What is action filter in 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.


1 Answers

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 
like image 176
Filip W Avatar answered Jan 03 '23 14:01

Filip W