【发布时间】:2020-02-13 15:48:59
【问题描述】:
我想在 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 调用操作实例化是否安全?
编辑:我将代码更改为此,现在看起来请求是共享的(什么??),当我尝试添加键值对时出现异常: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;
}
}
【问题讨论】:
-
给你的类一个构造函数。在其上放置断点,并在调试器中解决