2011-10-20 86 views
1

我的web.config中的连接字符串的加密功能有问题。在web.config中加密的连接字符串发生错误

加密完美!但只要启用加密,我将失去会话变量内容(会话变量上的空例外)。

当我停用web.config中连接字符串的加密时,一切都恢复正常。

这里是我的连接字符串的加密代码:

#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 

万分感谢您的帮助!

+0

我的代码基于以下网站:http://msdn.microsoft.com/en-us/library/89211k9b%28v=vs.80%29.aspx –

回答

1

错误来自设计错误。

下面是解:

  • 首先,加密必须以避免向数据库发出请求时每次都保存加密/解密从应用外部制成。

然后:

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"); 
    } 
} 

这样一来,在连接字符串在内存中解密,并不会产生任何问题使用,且避免许多无用的读取和写入到web.config。

相关问题