Prafulla sahu
Prafulla sahu

Reputation: 57

How to Get number of hits to the Web API method

I have an application there, I am using Web API calls for all my operations.

Now I have a requirement that, I need to track down our API calls, means how many times my API got called and which method called how many times. Every information I need to insert into the database for future response too.

Anyone has any idea how to achieve? Please share.

What I am thinking:

In global.asax under application_beginrequest I will check the url and will try to find the API method name.

Then the method name can be pushed to the DB by doing an asynchronous call.

Note:
Does it will slow down API performance?,

Upvotes: 0

Views: 1802

Answers (1)

Padraic
Padraic

Reputation: 667

Use an ActionFilter. You do not want to litter your code with logging.

public class MyLoggingFilter: ActionFilterAttribute 
{


    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        Log...
       //actionContext.ActionDescriptor.ActionName
        //actionContext.ControllerContext.ControllerDescriptor.ControllerName;
    }

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        Log...
    }
}

Then you should register the action filter for all controllers in your WebApiConfig

public static void Register(HttpConfiguration config)
{
        // Web API configuration and services

        config.Filters.Add(new MyLoggingFilter());

    config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
}

Then consider using a Logging framework like Log4Net or NLog - these frameworks will have appenders to log to any storage type (SQL, to file, whatever). These frameworks will log asynchronously so will not slow down the execution of your requests.

Upvotes: 1

Related Questions