带有 Web.API 2 的 MiniProfiler;是否有全局魔术请求上下文对象?

Rya*_*vis 5 httpcontext action-filter mvc-mini-profiler asp.net-web-api

我正在尝试在我的 web api 站点上设置 MiniProfiler,并且很难MiniProfiler.Current开始工作。

我按照 miniprofiler.com 上的指示,在 global.asax 中有以下内容:

protected void Application_Start()
{
  MiniProfilerEF6.Initialize();
  // other setup
}
protected void Application_BeginRequest() {
  // need to start one here in order to render out the UI
  MiniProfiler.Start();
}
protected void Application_EndRequest() {
  MiniProfiler.Stop();
}
Run Code Online (Sandbox Code Playgroud)

这使用默认的WebRequestProfilerProvider,它将实际的配置文件对象存储在HttpContext.Current.Items.

当我要求时MiniProfiler.Current,它看起来像HttpContext.Current

当我请求我的 Web api URL 之一时:

  • Application_BeginRequest 创建分析器,将其存储在 HttpContext.Current
  • 在 web api 中MessageHandler,我可以看到HttpContext.Current
  • 在网络 apu 中IActionFilterHttpContext.Current现在为空,我的尝试MiniProfiler.Current.Step("controller:action")失败了
  • 我从各种服务运行的 EF 查询没有被记录,因为 miniprofiler 钩子依赖MiniProfiler.Current,它依赖HttpContext.Current,现在为空
  • Application_EndRequest触发,然后HttpContext.Current神奇地返回,因此它包装分析器并告诉我自请求开始以来已经过去了多长时间

我仔细研究了代码,我可以创建自己的IProfileProvider, 将探查器对象存储在比 更可靠的地方HttpContext.Current,但我不知道那可能在哪里。

我花了几个小时来尝试,但找不到可行的解决方案。问题:

  • IProfileProvider是一个全局变量; MVC 或 Web API 管道中的所有工作线程都必须使用相同的IProfileProvider
  • 我可以在 web api RequestContext.Properties 中挖掘以提取该请求的 HttpContext,但这并没有真正的帮助,因为 myIProfileProvider在整个应用程序中是全局的;如果我告诉它在 HttpContext A 中存储配置文件,那么对其他 HttpContext 的任何同时请求都会污染配置文件
  • 由于异步/等待动态重用线程,我不能依赖任何类型的线程存储
  • 我无法将探查器对象粘贴到 Ninject 绑定中,InRequestScope因为InRequestScope它似乎不适用于 web api 2.1,但即使我可以
  • 每个人都说HttpRequestMessage.Properties是 new HttpContext.Current.Items,但同样IProfileProvider是一个全局变量,我不知道有什么方法可以确保每个请求都在查看它们的 version HttpRequestMessageMiniProfiler.Current可以从任何地方调用,所以我猜全局IProfileProvider必须以某种方式检查调用堆栈并找到HttpRequestMessage那里?这听起来很疯狂。

我不知所措。我真正想要的是一个特殊的变量

Rya*_*vis 2

把问题放在一起的过程我就弄清楚了。HttpContext.Current当您异步/等待事物时可能会迷失:为什么等待后 HttpContext.Current 为 null?

我必须对那里列出的 web.config 进行更改,并调整我的过滤器以Miniprofiler.Current在任何await操作之前使用。

还在https://www.trycatchfail.com/2014/04/25/using-httpcontext-safely-after-async-in-asp-net-mvc-applications/进行了讨论