Reputation: 905
I created a MVC project with WebAPI. I created a Controller (derivered from ApiController) and added the following line
string connstring = System.Configuration.ConfigurationManager.ConnectionStrings["isrOAK"].ToString();
and it throws a null exception, "Object reference not set to instance of an object".
However, there is a HomeController (derived from Controller) which was automatically added to the project. The connection string works.
Any idea why and how to get it to work on the derived Api Controller?
UPDATE: I am using a UNIT TEST project to test the WebAPI project. I call the HomeController Index() from the unit testing method and it is not throwing the same exception. What is needed in the Unit Testing project to make the get connection string work?
Upvotes: 1
Views: 830
Reputation: 64
To access connection string:
var conifg = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"];
and add key in your web.config file as below:
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-MvcApplication1-20150716202930;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-MvcApplication1-20150716202930.mdf" providerName="System.Data.SqlClient" />**
Upvotes: 0
Reputation: 914
System.Configuration.ConfigurationManager.ConnectionStrings["isrOAK"] returns a ConnectionStringSettings object. Use .ConnectionString to get the actual connection string.
string connstring = System.Configuration.ConfigurationManager.ConnectionStrings["isrOAK"].ConnectionString;
Upvotes: 2