存储在 web.config 文件中的连接字符串无法打开 SQL 服务器连接

Connection string stored in web.config file doesn't open SQL Server connection

我正在尝试学习使用 VS2015,并且我在 Internet 上看到了许多与此问题相关的类似帖子,其中 none 让我更接近于解决方案。

我正在尝试写入 SQL 服务器数据库并测试了我的数据库和连接字符串并确认它们都运行良好。

除此之外,我进入 web.config 并为所述连接字符串创建了一个定义:

<connectionStrings>
    <add name="Name" 
         connectionString="Data Source=<desktopname>\SQLEXPRESS01;Integrated Security=SSPI;Initial Catalog=Database1"/>
</connectionStrings>

据我所知这工作正常...

但是,当我如下声明字符串时:

MyConnectionString = ConfigurationManager.ConnectionStrings["Name"].ConnectionString;

不知何故returns无法理解:

SqlConnection iData = new SqlConnection(myConnectionString);

当我尝试 "open" 连接失败时...尽管在 C# 代码中这样声明时完全相同的连接字符串有效:

   SqlConnection iData = new SqlConnection("Data Source=<desktopname>\SQLEXPRESS01;Integrated Security=SSPI;Initial Catalog=Database1");

有没有人有什么想法?

据我所知,问题在于如何处理从 web.config 到字符串再到 SqlConnection 的信息。

值得注意的是,除非我使用该字符串作为连接字符串,否则一切都运行完美...

提前致谢!

尝试在您的“< 添加名称”

中添加:providerName="System.Data.SqlClient"
<add name ="Name" connectionString="Data Source=<desktopname>\SQLEXPRESS01;Integrated Security=SSPI;Initial Catalog=Database1"  providerName="System.Data.SqlClient"/>

在 C# 中,反斜杠需要加倍,因为编译器将反斜杠视为转义字符。然后 \ 在运行时实际使用的字符串中编译为 \

在 XML 中不是这种情况,它使用不同的解析器,因此在 Web.Config 中你应该使用单个 \:

<add name="Name" connectionString="Data Source=<desktopname>\SQLEXPRESS01;Integrated Security=SSPI;Initial Catalog=Database1"/>

除此之外,您可能还需要添加 providerName="System.Data.SqlClient":

<add
    name="Name"
    connectionString="Data Source=<desktopname>\SQLEXPRESS01;Integrated Security=SSPI;Initial Catalog=Database1"
    providerName="System.Data.SqlClient"
/>

参考: https://msdn.microsoft.com/en-us/library/bf7sd233(v=vs.85).aspx