MegaTron MegaTron - 20 days ago 5x
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:

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

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

Why I cannot get connectionString from web.config?


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