MegaTron MegaTron - 1 month ago 15
C# Question

Error while trying to get connectionString from web.config

I have a SelfHosted WCF service and when I'm trying to read connection string from web.config file

string conn = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;


then I'm getting an error:


Object reference not set to an instance of an object.


My Web.config:

<configuration>
<connectionStrings>
<add name="MyConnectionString" connectionString="server=192.168.1.2;database=TestDB;uid=sa;pwd=saas" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
...


I tried to use the
WebConfigurationManager
as described in this question, but it did not help.

Why I cannot get connectionString from web.config?

Answer

I found the solution. It was my fault. In the VS solution I have 2 projects: First(WCF service) and Second(Console app that hosted my service).

The problem was that I added connectionStrings to the First project in web.config file!

After I added the connectionStrings to the Second project in app.config file, everything works fine

Comments