来自web.config的连接字符串失败,其中相同的硬编码字符串成功(带有C#的ASP.NET)

时间:2011-05-09 08:54:29

标签: c# asp.net web-config connection-string

我从配置文件传入的连接字符串出现了一些奇怪的行为。

我正在构建一个n层网站(使用C#类库和一个C#ASP.NET网站),并获得一个基本页面,用于从数据库(Microsoft SQL Server 2008)中提取数据,通过数据访问和业务层并将其显示在网页上。这在数据访问层中使用硬编码连接字符串是成功的。

为了改进体系结构,我将连接字符串删除到网站中的web.config文件。从web.config成功检索连接字符串,但是使用此连接字符串调用.open()方法时连接失败。

使用此构造函数,数据库连接可以正常工作:

public PathwayAccess() {
    connectionString = "server=.\\MYSERVER;database=MyDatabase;Integrated Security=SSPI;";
}

使用以下代码,检索字符串,可以写出调试并且看起来很好,并且不会抛出异常:

编辑 web.config

<?xml version="1.0"?>
<configuration>

    <system.web>
      <compilation debug="false" targetFramework="4.0" />
      <customErrors mode="Off"/>
    </system.web>

  <connectionStrings>
    <clear/>
    <add name="MySqlClientConnectionString"
     providerName="System.Data.SqlClient"
     connectionString="server=.\\MYSERVER;database=MyDatabase;Integrated Security=SSPI;" />
    <!-- EDIT: problem was the escaped \ in the connection string:
               should have been .\MYSERVER instead of .\\MYSERVER as
               it doesn't need to be escaped in the config file -->
  </connectionStrings>

</configuration>

和我的数据访问类的新构造函数:

public PathwayAccess() {

    ConnectionStringSettingsCollection settings = ConfigurationManager.ConnectionStrings;
    if (settings != null) {
        foreach (ConnectionStringSettings cs in settings) {
            if (cs.Name == "MySqlClientConnectionString" && cs.ProviderName == "System.Data.SqlClient") {

                connectionString = cs.ConnectionString.ToString();
                return;
            }
        }
        throw new Exception("The SqlClient connection string named 'MySqlClientConnectionString' was not found in connection.config. "
            + "Found " + settings.Count + " connection strings");
    } else {
        throw new Exception("Could not retrieve the connection string from a configuration file. Check the connection strings section of the relevant config file");
    }
}

但是下面的代码将在上面的第一个构造函数之后工作,但在第二个之后抛出InvalidOperationException(带有“Instance failure”消息):

myConnection = new SqlConnection(connectionString);
myConnection.Open();

我对此感到非常困惑 - 由于某种原因,来自配置文件的连接字符串看起来与硬编码的连接字符串相同,但表现不同。知道可能会发生什么吗?

1 个答案:

答案 0 :(得分:2)