我有一個查詢數據庫的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
,但我仍然無法獲取字符串。我如何得到字符串?
在您的web.config文件中,是一個節點下的節點嗎? –
只需嘗試ConfigurationManager.ConnectionStrings [「ConnString」]。ToString() – ckv
@RyanWeir - 是的,它是節點的直接子節點。 –
Jonathan