C# Web API通过action filter属性获取请求时间

C# Web API通过action filter属性获取请求时间,c#,asp.net-web-api,actionfilterattribute,C#,Asp.net Web Api,Actionfilterattribute,我想知道是否可以通过自定义操作筛选器属性获取请求的时间?我有以下资料: public sealed class FooFilterAttribute : ActionFilterAttribute { public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { if (actionExecutedContext.Response != null)

我想知道是否可以通过
自定义操作筛选器属性
获取请求的时间?我有以下资料:

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


谢谢。

在执行OnActionExecuted时,我认为框架不再知道这个值了。但是您可以在操作执行中获取它,并将其存储在请求中。大概是这样的:

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);
}

OnActionExecuted
的时候,我认为框架不再知道这个值。但是您可以在操作执行中获取它,并将其存储在请求中。大概是这样的:

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);
}

太好了,谢谢你。不过,看起来有点脏。使用DelegatingHandler方法与添加到properties集合的方法相同吗?非常感谢。不过,看起来有点脏。使用DelegatingHandler方法与添加到properties集合的方法相同吗?