我想知道是否可以通过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
值。
感谢。
答案 0 :(得分:0)
在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);
}