【问题标题】:Error occurs with an encrypted connection string in web.configweb.config 中的加密连接字符串发生错误
【发布时间】:2011-12-12 03:10:14
【问题描述】:

我在 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

感谢您的帮助!

【问题讨论】:

标签: c# asp.net config


【解决方案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 的许多无用读取和写入。

【讨论】:

    猜你喜欢
    • 2012-06-18
    • 2010-12-14
    • 1970-01-01
    • 2011-08-19
    • 2012-05-31
    • 1970-01-01
    • 2011-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多