Application_BeginRequest 没有触发缓存结果?

Application_BeginRequest not firing for cached results?

我正在编写 ASP.NET MVC 应用程序,使用 IIS 7.5 作为 Web 服务器。 我想在任何请求开始时打开一个数据库连接,并在请求结束时关闭此连接。

因此,在global.asax中我指定了成员

Public Shared conn As OleDbConnection

在 Application_BeginRequest 处理程序中,我这样打开连接:

Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
   Dim strConn As String = "myConnectionString..."
   conn = New OleDbConnection(strConn)
   conn.Open()
End Sub 'Application_BeginRequest

然后在 Application_EndRequest 处理程序中关闭它:

Sub Application_EndRequest(ByVal sender As Object, ByVal e As EventArgs)
   conn.Close()
   conn.Dispose()
End Sub 'Application_EndRequest

然后,也许在 HomeController 的 Index() 方法中,我使用 global.asax:

提供的 Db 连接
Dim _conn As OleDbConnection = MvcApplication.conn
'[then get or set data in the DB...]

我现在遇到一件奇怪的事情:当我从服务器完全重新加载页面时,数据库连接正确打开。当 IIS 从缓存中传送页面时,数据库连接不是开放式的,我收到一个错误(尽管从我的报告工具看来,输入了 Application_BeginRequest 处理程序)。有没有办法克服这个问题?我已经尝试通过 HTML 元标记并利用此处提供的以下问答来设置缓存控制:How to switch off caching for MVC requests but not for static files in IIS7? 问题仍然存在。谁能帮忙? 非常感谢, niewi

共享变量是……跨请求共享的。这意味着两个并发请求将破坏彼此的连接。这就是您可能正在观察的内容。

将连接存储在 HttpContext.Items 中。