asp.netencryptioniis-8webconfigurationmanagerweb-config-encryption

Web config encryption using DataProtectionConfigurationProvider is not working on Production


I have used DataProtectionConfigurationProvider to encrypt the connection strings of web config, which is working fine in local.

But when I uploaded the code to production, the web config is not getting encrypted.

I have used following code:

Configuration config =
                WebConfigurationManager.OpenWebConfiguration("/");
            // Let's work with the <connectionStrings> section
            ConfigurationSection connectionStrings = config.GetSection("connectionStrings");
            if (connectionStrings != null)
            {

                // Only encrypt the section if it is not already protected
                if (!connectionStrings.SectionInformation.IsProtected)
                {
                  // Encrypt the <connectionStrings> section using the 
                    // DataProtectionConfigurationProvider provider
                    connectionStrings.SectionInformation.ProtectSection(
                        "DataProtectionConfigurationProvider");
                    config.Save();
                }
            }

I traced the code by putting the logs and found that !connectionStrings.SectionInformation.IsProtected condition is not working .

Any help would be appreciable!!


Solution

  • The problem is due to "/" path in WebConfigurationManager.OpenWebConfiguration("/"). My application is hosted inside virtual directory.

    Using below code solved the issue:

      Configuration config = WebConfigurationManager.OpenWebConfiguration("~");