user1841243
user1841243

Reputation: 1713

Why can I not find an AppSetting in my Web.Config with WebConfigurationManager?

I have 2 projects in my solution. 1 is an MVC Web application The other is an empty website with a Web Service

Yesterday I added a setting via right-click on the Web Service project and go to properties => add settings manually.

This creates a settings file and adds the settings to Web.Config.

today I manually modified the Web.config file (I'm not sure this is the cause) but for some reason the following code cannot get my setting out of my Web.Config:

string connstring = WebConfigurationManager.AppSettings["someString"];

It just returns null

The setting name is correct. The MVC-projects also has settings added in the same manner, there I can get all settings without any problems.

Things I've tried:

Another strange thing that I notice is the following:

When I type "WebConfigurationManager" in the immediate window => it looks like there are 0 AppSettings in it. It also indicates that I have 2 connectionstrings while they really are not there (no where to be found in the solution if I perform Ctrl+Shift+F): This is the connectionstring "WebConfigurationManager.ConnectionStrings[0]" returns:

ConnectionString: "data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"

I would almost think it's opening the wrong Web.config (but not one in any of my projects since the connectionstring here above does not exist in my solution)

Thanks for any tips !!

Extra info, contents of web.config:

....

<applicationSettings>
    <SomeWebServices.Properties.Settings>
        <setting name="someString" serializeAs="String">
            <value>DATA SOURCE=abcdefg;USER ID=ABC;PASSWORD=abc987</value>
        </setting>
        <setting name="someOtherString" serializeAs="String">
            <value>DATA SOURCE=abcde;USER ID=ABC;PASSWORD=abc654</value>
        </setting>
    </SomeWebServices.Properties.Settings>
</applicationSettings>

Upvotes: 1

Views: 3042

Answers (2)

Cros
Cros

Reputation: 4377

Since you are using applicationSettings and not appSettings in you web.config you'll need to access your setting via Properties.Settings.Default.someString

If you want to use string connstring = WebConfigurationManager.AppSettings["someString"]; you'll have to add the setting in the appSettings part of your web.config.

Edit:
If what you really want is somewhere to put your connection strings you should follow BilginAksoy's answer and use the connectionStrings part of your web.config.

Upvotes: 1

BilginAksoy
BilginAksoy

Reputation: 107

If you use .NET 3.5 or above, do not use appsettings in web.config. Instead use the connectionStrings section in web.config.

try this web.config

<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>

Upvotes: 1

Related Questions