【问题标题】:Web API get time of request via action filter attributeWeb API 通过操作过滤器属性获取请求时间
【发布时间】:2015-10-15 03:51:55
【问题描述】:

我想知道是否可以通过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 值。

谢谢。

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 非常感谢您。不过,好像有点脏。使用 DelegatingHandler 的方式和添加到属性集合中是一样的吗?
    猜你喜欢
    • 2014-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    • 1970-01-01
    • 1970-01-01
    • 2013-08-22
    • 1970-01-01
    相关资源
    最近更新 更多