第一个 Web API 请求触发执行 Application_Start

First Web API request triggers execution of Application_Start

我有一个还集成了 Web API 的 Web 应用程序。就在今天,我发现自己很惊讶地看到 Web 上的第一个 REST 请求 API 重新触发了 Application_Start 的执行(尽管在启动网页时已经 运行 ).阅读 and ASP.NET Application Life Cycle Overview 后,似乎 REST 请求正在生成一个新的 HttpApplication

此外,在 MSDN 上它说:

The first time that an ASP.NET page or process is requested in an application, a new instance of the HttpApplication class is created. However, to maximize performance, HttpApplication instances might be reused for multiple requests.

在我看来,每个请求都可能产生一个新的 HttpApplication,因此,Application_Start 必须以可重入或幂等方式编写。这个结论对吗?

在我的具体案例中,我在 Application_Start 中初始化一个日志写入器,但第二次失败了,因为该文件已被使用。我想在应用程序池回收的情况下,这不会成为问题,因为资源在这期间被释放了。

您可以进一步阅读所提供的 link

The Application_Start and Application_End methods are special methods that do not represent HttpApplication events. ASP.NET calls them once for the lifetime of the application domain, not for each HttpApplication instance.

所以没必要写成Application_Start可重入或者幂等的方式

另外Application_Start没有调用IIS的回收。当应用程序实际由 IIS 加载时,它在回收后的第一个请求上被调用。

关于您的错误,请确保您在 Application_End 上处理了记录器,以便释放文件句柄。