C# HttpContext.Current.Items似乎在请求之间共享-可能是信号器问题?
我试图在ActionFilter中编写一些日志代码,以确定处理某些操作需要多长时间。代码如下所示:C# HttpContext.Current.Items似乎在请求之间共享-可能是信号器问题?,c#,asp.net-mvc,signalr,C#,Asp.net Mvc,Signalr,我试图在ActionFilter中编写一些日志代码,以确定处理某些操作需要多长时间。代码如下所示: public override void OnActionExecuting(ActionExecutingContext filterContext) { var stopwatch = new Stopwatch(); stopwatch.Start(); HttpContext.Current.Items.Add("Stopwatch", stopwatch); }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
HttpContext.Current.Items.Add("Stopwatch", stopwatch);
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var stopwatch = HttpContext.Current.Items["Stopwatch"] as Stopwatch;
if (stopwatch != null)
{
stopwatch.Stop();
var millis = stopwatch.ElapsedMilliseconds;
// Code to log here
}
}
它在这里的FilterConfig.cs
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new LogRequestMetricFilter());
}
并在Autofac中配置为属性注入:
builder.Register(c => new LogRequestMetricFilter()).PropertiesAutowired()
.AsActionFilterFor<Controller>().InstancePerRequest();
builder.Register(c=>newlogrequestmetricfilter()).PropertiesAutowired()
.AsActionFilterFor().InstancePerRequest();
这基本上可以正常工作,但是在某些情况下,当HttpContext.Current.Items.Add(“Stopwatch”,Stopwatch)时当抛出错误时,调用代码>
项目已添加。字典中的键:添加了“秒表”键:“秒表”
这意味着请求之间正在共享HttpContext.Current
。这似乎发生在使用signer的方法上,但据我所知,它们已经完成了,并且无论如何它不应该共享HttpContext
有人能解释一下为什么在Items Dictionary中已经有一个项具有该键时调用OnActionExecuting
吗?作为旁白,我已经通过调用HttpContext.Current.Items.Remove(“秒表”)修复了异常代码>在OnActionExecuted
中执行,但我仍然好奇它是如何在第一次执行中产生的place@ste-fe我建议配置错误。你能显示你的启动吗?@tester启动?这不是netcore应用程序。@ste-fe:在哪里配置应用程序filter@Tester在AppStart.FilterConfig.cs中,我通过调用HttpContext.Current.Items.Remove(“秒表”)修复了异常代码>在OnActionExecuted
中执行,但我仍然好奇它是如何在第一次执行中产生的place@ste-fe我建议配置错误。你能显示你的启动吗?@tester启动?这不是netcore应用程序。@ste-fe:在哪里配置应用程序filter@Tester在AppStart.FilterConfig.cs中