0

这是我的 global.asax 的 VB 代码

<%@ Application Language="VB">
<script runat="server">

Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
    ' Code that runs on application startup
    Application("CS") = "server=myServer; user id=myUser; password=MyPaas; database=myData; pooling=true"
End Sub

Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
    ' Code that runs on application shutdown
    Application("CS") = ""

End Sub

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
    ' Code that runs when an unhandled error occurs
End Sub

Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
    ' Code that runs when a new session is started
End Sub

Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
    ' Code that runs when a session ends.
    ' Note: The Session_End event is raised only when the sessionstate mode
    ' is set to InProc in the Web.config file. If session mode is set to StateServer
    ' or SQLServer, the event is not raised.
End Sub

</script>

我在 VB 中这样称呼这个值: Dim objConn As New SqlConnection(Application("CS"))

如何在 C# ASP.NET 中进行此调用?

4

1 回答 1

0

等效的 C# 代码将是:

SqlConnection objConn = new SqlConnection(Application["CS"]);

请注意“CS”周围的 [] 而不是 ()。

或者,您可以在 using 块中执行此操作:

using (SqlConnection objConn = new SqlConnection(Application["CS"]))
{

    // Do your data access here
}

using 块确保调用 dispose (即使遇到异常)。有关 using 语句的更多信息,请参阅using 语句(C# 参考)

虽然我想知道 - 你为什么将 C# 与用 VB.NET 编写的 Global.asax 文件一起使用?

于 2012-09-29T05:31:37.810 回答