2013-07-08 60 views
6

我有一個查詢數據庫的Visual Studio 2012 ASP.NET MVC應用程序。我被告知將連接字符串保存在web.config文件中是一種很好的做法。所謂ConnString連接字符串位於:Visual Studio 2012 ASP.NET MVC連接字符串Web.Config

<connectionStrings> 
     <add name="ConnString" connectionString="Data Source=IP_OF_SERVER,PORT; Initial Catalog=DATABASE_NAME; UID=USERNAME; pwd=PASSWORD; Integrated Security=True;"/> 
    </connectionStrings> 

在C#中,我想要得到的連接字符串,我用:

String connStr = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString; 

的應用程序死在這條線上,並拋出以下異常:

Object reference not set to an instance of an object. System.NullReferenceException: Object reference not set to an instance of an object. 

我已經包括:

using System.Configuration; 

位於頁面頂部,但仍然失敗。我嘗試使用using System.WebConfiguration,但我仍然無法獲取字符串。我如何得到字符串?

+1

在您的web.config文件中,是一個節點下的節點嗎? –

+0

只需嘗試ConfigurationManager.ConnectionStrings [「ConnString」]。ToString() – ckv

+0

@RyanWeir - 是的,它是節點的直接子節點。 – Jonathan

回答

2

更改您的web.config文件,包括providerName="System.Data.SqlClient"因爲這樣在連接字符串的屬性:

<connectionStrings> 
     <add name="ConnString" connectionString="Data Source=IP_OF_SERVER,PORT; Initial Catalog=DATABASE_NAME; UID=USERNAME; pwd=PASSWORD; Integrated Security=True;" providerName="System.Data.SqlClient" /> 
    </connectionStrings> 
+0

謝謝,這個問題實際上是我使用錯誤的web.config文件! – Jonathan

1

你錯過了您的連接字符串添加providerName="System.Data.SqlClient"

更改您的接法字符串:

<connectionStrings> 
      <add name="ConnString" connectionString="Data Source=IP_OF_SERVER,PORT; Initial Catalog=DATABASE_NAME; UID=USERNAME; pwd=PASSWORD; Integrated Security=True;" providerName="System.Data.SqlClient" /> 
     </connectionStrings> 

問候

+0

這不應該影響ConfigurationManager,因爲它會忽略提供者。這隻能在ADO.net中使用 –

1

我沒有新的來回答這個問題,但我想給一些解釋,

System.Data.SqlClient 

其.NET框架SQL Server的數據提供者。在web.config中,應該將System.Data.SqlClient作爲providerName屬性的值。它是您正在使用的.NET Framework數據提供程序。

,如果你要連接MySQL的應用程序,那麼你可以使用所需的

MySql .Net Connector 

它,但在你的情況下,其丟失的,這就是爲什麼您收到錯誤消息。

你可以閱讀更多關於(這裏)[http://msdn.microsoft.com/en-US/library/htw9h4z3(v = VS.80).aspx]希望它能讓你更好地理解錯誤你做了,你喲修復它。

<configuration> 
    <connectionStrings> 
    <add name="Northwind" 
     connectionString="Data Source=Data Source=IP_OF_SERVER,PORT; Initial Catalog=DATABASE_NAME; UID=USERNAME; pwd=PASSWORD; Integrated Security=True;" 
     providerName="System.Data.SqlClient" /> 
    </connectionStrings> 
</configuration>