Mike Verrier
Mike Verrier

Reputation: 484

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 !

Upvotes: 1

Views: 368

Answers (1)

Mike Verrier
Mike Verrier

Reputation: 484

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.

Upvotes: 1

Related Questions