eagle275
eagle275

Reputation: 125

How to access the web.config for a WCF service hosted in IIS from the code "inside" the service

As headline says, after redefining our goals we shrunk our 2 services into 1, which is hosted in IIS 10.0 on an Windows 2019 server using BasicHttpBinding - I found out by trial and error that the main problem I had before was caused by said server not being part of the local DNS service. So I re-wrote the connection string to our database server using plain IP. This works. To make configuration easier I added a new line to the section appSettings in my services' web.config

<appSettings>
<add key="Database" value="<whole connection string>"/>

I found a code-snippet provided by Microsoft to access the web.config - but it seems to parse the wrong web.config as my data is missing / the whole section seems empty when parsing ...

my used code

        //Scan Thru the keys and use the Configuration Manager to make this happen
        System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration(null) as System.Configuration.Configuration;
        // Get the appSettings.
        KeyValueConfigurationCollection appSettings = config.AppSettings.Settings;
        String ret="";
        foreach (string key in appSettings.AllKeys)
        {
            //Get your key
            string tmpKey = appSettings[key].Value;

            switch (key)
            {
                case "Database":
                    ret = tmpKey;
                    break;
            }
        }

then I would use "ret" to build the actual connection ... but so far that fails since above code doesn't find "anything" in appSettings.AllKeys (collection is empty) Any hints towards working code would be greatly appreciated. Or is null the wrong parameter although the code hints suggest that null points to the original web.config

Upvotes: 1

Views: 905

Answers (2)

Abraham Qian
Abraham Qian

Reputation: 7522

Normally, you could use the below code snippets to obtain the value in the AppSettings section.

var result = ConfigurationManager.AppSettings["mykey"];
            Console.WriteLine(result.ToString());

Here is an official example and explanation.
https://learn.microsoft.com/en-us/dotnet/api/system.configuration.configurationmanager.appsettings?view=netframework-4.8
https://learn.microsoft.com/en-us/dotnet/api/system.configuration.configurationmanager?view=netframework-4.8
Feel free to let me know if there is anything I can help with.

Upvotes: 2

Scott Hannen
Scott Hannen

Reputation: 29212

You should be able to access an app setting using

ConfigurationManager.AppSettings["Database"]

Upvotes: 1

Related Questions