I have a Visual Studio 2012 ASP.NET MVC application which queries a database. I've been told it's good practice to keep the connection string in the web.config file. The connection string called ConnString
is located:
<connectionStrings>
<add name="ConnString" connectionString="Data Source=IP_OF_SERVER,PORT; Initial Catalog=DATABASE_NAME; UID=USERNAME; pwd=PASSWORD; Integrated Security=True;"/>
</connectionStrings>
In C# where I want to get the connection string, I use:
String connStr = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
The app dies on this line and throws the following exception:
Object reference not set to an instance of an object. System.NullReferenceException: Object reference not set to an instance of an object.
I have included:
using System.Configuration;
at the top of the page, but it still fails. I tried using using System.WebConfiguration
, but I can still not get the string. How do I get the string?
Change your web.config file to include providerName="System.Data.SqlClient"
as an attribute on the connection string like this:
<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>
You've missed to add providerName="System.Data.SqlClient"
on your connection string.
Change your connectiong string to:
<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>
Regards
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With