是否为每个动作实例化了ActionFilterAttribute?

问题描述 投票:0回答:2

我想在ActionFilterAttribute中有一个仅与它所驻留的动作有关的字段,例如

    public class TimedAction : ActionFilterAttribute
    {
        long start, end;

        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            start = Stopwatch.GetTimestamp();

            base.OnActionExecuting(actionContext);
        }

        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnActionExecuted(actionExecutedContext);

            end = Stopwatch.GetTimestamp();
        }
    }

是否可以安全地假设将为每个API调用操作实例化TimedAction?

编辑:我将代码更改为此,现在看来请求是共享的(是什么?),当我尝试添加键值对时出现异常:An item with the same key has already been added.

        public override void OnActionExecuting(HttpActionContext context)
        {
            var start = Stopwatch.GetTimestamp();

            context.Request.Properties.Add(new KeyValuePair<string, object>("Stopwatch", start));

            base.OnActionExecuting(context);
        }

        public override void OnActionExecuted(HttpActionExecutedContext context)
        {
            base.OnActionExecuted(context);

            var end = Stopwatch.GetTimestamp();

            object o;
            long start = 0;
            if (context.Request.Properties.TryGetValue("Stopwatch", out o))
            {
                start = (long)o;
            }
        }
c# asp.net rest webapi
2个回答
3
投票

请勿这样做,因为属性是静态定义的。您需要将其存储在请求中,例如HttpContext.Current.Items["SomeKey"]

public override void OnActionExecuting(HttpActionContext actionContext)
{
    HttpContext.Current.Items["Now"] = DateTime.UtcNow;

    base.OnActionExecuting(actionContext);
}

public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
    var beginning = (DateTime) HttpContext.Current.Items["Now"];

    var end = DateTime.UtcNow;

    var interval = end - beginning;

    base.OnActionExecuted(actionExecutedContext);
}

0
投票

显然,我所做的(参见OP中的代码)与@RicardoPeres的方法没有区别。

问题是我不小心将属性两次设置为方法。

但是我觉得里卡多的版本比我的更好,所以我保留了它。

© www.soinside.com 2019 - 2024. All rights reserved.