c# - ActionFilterAttribute 是否为每个 Action 实例化?

标签 c# asp.net rest webapi

我想在 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();
        }
    }

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

编辑:我将代码更改为此,现在看来请求是共享的(什么??),当我尝试添加键值对时出现异常:已添加具有相同键的项目。

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

最佳答案

不要那样做,因为属性是静态定义的。您需要将其存储在请求中,例如 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);
}

关于c# - ActionFilterAttribute 是否为每个 Action 实例化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60211723/

相关文章:

c# - WPF - 如何动态更改窗口的语言属性

c# - 如何在 6 条记录后用 "question mark character"替换 gridview 的值?

c# - Windows Azure Blob 中来自 "subfolders"的输出图像

asp.net - Redis 抛出异常 "System.OutOfMemoryException"

c# - 单例的一生

php - 防止 Shopsystem 的 "pending"付款

c# - Hook API 函数 GetSystemMetrics

c# - 在 Viewmodel 中接收 RaisePropertyChanged (MVVM Light)

java - Java中URI路径参数解析

rest - Power BI REST API : The remote server returned an error