Web API通过操作过滤器属性获取请求时间

时间:2015-07-24 12:56:10

标签: c# asp.net-web-api actionfilterattribute

我想知道是否可以通过custom action filter attribute获取请求的时间?我有以下内容:

public sealed class FooFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        if (actionExecutedContext.Response != null)
        {
            var start = actionExecutedContext.Request.Headers.Date; //this is null
            var end = actionExecutedContext.Response.Headers.Date;                
        }
    }
}

我想知道处理请求所花费的总时间,但我似乎无法访问请求启动时的DateTime值。

感谢。

1 个答案:

答案 0 :(得分:0)

OnActionExecuted时,我认为框架不再知道该值。但您可以在OnActionExecuting中获取它并将其存储在请求中。像这样:

public override void OnActionExecuting(HttpActionContext actionContext)
{
    actionContext.Request.Properties.Add(this.GetType().FullName, Stopwatch.StartNew());

    base.OnActionExecuting(actionContext);
}

现在,您可以在操作结束时获取 值:

public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
    Stopwatch stopWatch = null;
    if (actionExecutedContext.Request.Properties.ContainsKey(this.GetType().FullName))
        stopWatch = actionExecutedContext.Request.Properties[this.GetType().FullName] as Stopwatch;
    if (stopWatch != null)
    {
        var elapsedTime = stopWatch.ElapsedMilliseconds;
        // do something with that value
    }

    base.OnActionExecuted(actionExecutedContext);
}