Pankaj Kapare
Pankaj Kapare

Reputation: 7812

ASP.Net Web Api action execution time

I have several web api action methods for which I want to capture execution start time and end time. I thought using ActionFilter's OnActionExecuting and OnActionExecuted method I can capture it from centralized place. Idea is to capture execution start time and add it to response headerin OnActionExecuting method. Similarly capture execution end time and it to response header in OnActionExecuted method. Now problem here is in "OnActionExecuting" method its just start of request processing and response object is not initialized, I can not add response header. Why I want to do it using headers: In production I will send flag using request header to capture execution time when I need to and other time it wont capture those details. I don't want to use logging approach but http headers. I also don't want to write this code in individual action methods. Is there any place where I can store execution start time somewhere and I access it in OnActionExecuted method and add it to response header? I used following code but in OnActionExecuting Response object is NULL.

public class TestFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        //Response is not initialized yet. Hence this wont work.  
        actionContext.Response.Headers.Add("StartTime", DateTime.Now.ToLongTimeString());
        base.OnActionExecuting(actionContext);
    }

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        actionExecutedContext.Response.Headers.Add("StartTime", DateTime.Now.ToLongTimeString());
        base.OnActionExecuted(actionExecutedContext);
    }
}

Upvotes: 1

Views: 1917

Answers (1)

Pankaj Kapare
Pankaj Kapare

Reputation: 7812

I found way to store Request start time. In OnActionExecuting method I capture start time and is storing it on actionContext.Request.Properties as custom property. This stored value I am retrieving in OnActionExecuted method and setting it on Response header. Thought it may be helpful for someone who is looking for similar implementation.

Upvotes: 2

Related Questions