C# web.config中的加密连接字符串出错
我在web.config中的连接字符串的加密功能有问题 加密工作完美!但一旦启用加密,我就会丢失会话变量内容(会话变量上出现Null异常) 当我在web.config中停用连接字符串的加密时,一切都会恢复正常 以下是我的连接字符串加密代码:C# web.config中的加密连接字符串出错,c#,asp.net,config,C#,Asp.net,Config,我在web.config中的连接字符串的加密功能有问题 加密工作完美!但一旦启用加密,我就会丢失会话变量内容(会话变量上出现Null异常) 当我在web.config中停用连接字符串的加密时,一切都会恢复正常 以下是我的连接字符串加密代码: #region Constructeur static QueryManager() { Configuration config = WebConfigurationManager.OpenWebConfiguration("~"); Conne
#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
非常感谢你的帮助 该错误来自设计错误 以下是解决方案:
- 首先,必须从应用程序外部进行加密,以避免每次向数据库发出请求时都保存加密/解密
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的许多无用的读写。错误来自设计错误 以下是解决方案:
- 首先,必须从应用程序外部进行加密,以避免每次向数据库发出请求时都保存加密/解密
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进行许多无用的读写。我的代码基于此网站:我的代码基于此网站: