Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual Studio 2012 ASP.NET MVC Connection Strings Web.Config

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?

like image 369
Jonathan Avatar asked Jul 08 '13 14:07

Jonathan


2 Answers

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>
like image 106
Ryan Weir Avatar answered Oct 18 '22 05:10

Ryan Weir


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

like image 30
BizApps Avatar answered Oct 18 '22 04:10

BizApps