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

发布于 2024-11-06 01:52:32 字数 2378 浏览 3 评论 0原文

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

我正在构建一个 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 (带有消息“实例失败”):

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

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

I'm getting some strange behaviour with a connection string passed in from a config file.

I am building an n-tier website (with C# class libraries and a C# ASP.NET website), and got a basic page working what pulls some data from the database (Microsoft SQL Server 2008), through the data access and business tiers and displays it on a web page. This is successful with a hard-coded connection string in the data access tier.

To improve the architecture, I am removing the connection string to the web.config file in the website. The connection string is successfully retrieved from web.config, but the connection fails when the .open() method is called with this connection string.

With this constructor, the database connection works perfectly:

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

With the following, the string is retrieved, can be written out to debug and looks fine, and throws no exceptions:

EDIT 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>

and new constructor for my data access class:

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");
    }
}

But the following code will work after the first constructor above, but throws an InvalidOperationException after the second (with message "Instance failure"):

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

I'm very puzzled by this - for some reason the connection string from the config file looks identical to the hard-coded one, but behaves differently. Any idea what might be going on?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文