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

I have an ASP.NET MVC Visual Studio 2012 application that is querying a database. I was told that itโ€™s good practice to save the connection string in the web.config file. A connection string named 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 a connection string, I use:

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

The application 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 turned on:

 using System.Configuration; 

at the top of the page, but it still doesn't work. I tried using using System.WebConfiguration , but I still can not get the line. How to get a string?

+6
source share
3 answers

Modify the web.config file to include providerName="System.Data.SqlClient" as an attribute in the connection string as follows:

  <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> 
+2
source

You missed adding providerName="System.Data.SqlClient" to the connection string.

Change the connectiong line 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> 

Hello

+1
source

I have nothing new to answer this question, but I would like to give some explanation,

  System.Data.SqlClient 

Custom .NET Framework data provider for SQL Server. In web.config, you must have the value System.Data.SqlClient as the value of the providerName attribute. This is the .NET Framework data provider that you are using.

if you need to connect your application to MYSql, you can use

  MySql .Net Connector 

It is required, but in your case it is missing, so you get an error message.

You can find out more (here) [http://msdn.microsoft.com/en-US/library/htw9h4z3 (v = VS.80) .aspx] Hope this gives you a better idea of โ€‹โ€‹what kind of error you and you fix it.

  <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> 
+1
source

Source: https://habr.com/ru/post/948945/


All Articles