web.config中的connectionstring错误:System.InvalidOperationException:实例失败

时间:2015-09-12 13:00:16

标签: c# asp.net web-config

我正在使用带有C#和SQL Server Express 2014的Visual Studio Community Edition为数据库开发应用程序。

当我在Web.config文件中定义连接字符串时,如下所示:

<connectionStrings>
    <add name="connect" 
         connectionString="data source=PTW\SQLEXPRESS; Database=Mydb; integrated security=SSPI" 
         providerName="System.Data.SqlClient"/>
  </connectionStrings>

使用以下语句检索它:

string cs = ConfigurationManager.ConnectionStrings["connect"].ConnectionString;

我收到错误:

  

System.InvalidOperationException:实例失败。

但是当我在表单中定义连接字符串时,我没有得到错误,并且将建立连接。

如何解决此问题?

这里是我在web.config文件中的内容:

<configuration>
  <connectionStrings>
    <add name="connect" 
         connectionString="data source=PTW\SQLEXPRESS; Database=Mydb; integrated security=SSPI" 
         providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2"/>
    <httpRuntime targetFramework="4.5.2"/>
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"/>
    </compilers>
  </system.codedom>
</configuration>

这就是我在表格中的内容:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;

namespace GlobalCS
{
    public partial class Connect : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string cs = ConfigurationManager.ConnectionStrings["connect"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {
                con.Open();
                Label1.Text = "Connected";
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

问题来自SQL Server端,只是从microsoft(hotfixv4.microsoft.com)安装了SQL Server update(4),就是它,Done。