MegaTron MegaTron - 1 year ago 181
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?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download