简体   繁体   中英

Error occurs with an encrypted connection string in web.config

I have a problem with the encryption feature of my connection string in web.config.

The encryption works perfectly ! But as soon as the encryption is enabled I lose my Session variable content (Null exception on session variable).

When I deactivate the encryption of my connection string in the web.config, everything return to normal.

Here is my code for the encryption of the connection string :

#region Constructeur

static QueryManager()
{
  Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
  ConnectionStringsSection section = config.GetSection("connectionStrings") as 
                                     ConnectionStringsSection;

  if (section.SectionInformation.IsProtected)
  {
    section.SectionInformation.UnprotectSection();
    config.Save(ConfigurationSaveMode.Minimal);
  }

  if ((myConnectionString = 
       ConfigurationManager.ConnectionStrings["DBConnect"].ConnectionString) == null)
  {
    throw new ConfigurationErrorsException("Database server not configured");
  }

  section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
  config.Save(ConfigurationSaveMode.Minimal);            
}

#endregion

Thanks a million for your help !

The error comes from a design error.

Here is the solution :

  • First, the encryption has to be made externally from the application in order to avoid to save encryption/decryption each time a request to the database is made.

Then :

static QueryManager()
{

  Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
  ConnectionStringsSection section = config.GetSection("connectionStrings") as 
                                     ConnectionStringsSection;

  if (section.SectionInformation.IsProtected)
  {
    section.SectionInformation.UnprotectSection();
  }            

  myConnectionString = section.ConnectionStrings["DBConnect"].ConnectionString;

  if (unikSignConnectionString == null)
  {
    throw new ConfigurationErrorsException("Database server not configured");
  }
}

That way, the connection string is decrypted in memory and used without creating any problems and it avoid many useless read and write to the web.config.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM