简体   繁体   English

在Global.asax中以编程方式加密Web.Config

[英]Encrypt Web.Config Programmatically in Global.asax

I would like to check and then programmatically encrypt my web.config during the Application_Start (global.asax) if its not already encrypted. 我想在Application_Start(global.asax)期间检查并以编程方式加密我的web.config(如果尚未加密)。

protected void Application_Start()
{
    EncryptConfig.Encrypt("/Web.config");
}

And My Method 和我的方法

protected internal static void Encrypt(string applicationPath)
{
    private const string Provider = "RSAProtectedConfigurationProvider";
    private const string Section = "connectionStrings";

    var test = applicationPath;

    var confg = WebConfigurationManager.OpenWebConfiguration(applicationPath);
    var confStrSect = confg.GetSection(Section);

    if (confStrSect != null)
    {
        confStrSect.SectionInformation.ProtectSection(Provider);
        //confStrSect.SectionInformation.ForceSave = true;
        //confg.Save(ConfigurationSaveMode.Modified);
        confg.Save();
    }
}

I am getting the following exception which im having no luck resolving using Google and StackOverflow 我收到以下异常,使用Google和StackOverflow无法解决运气问题

An exception of type 'System.Configuration.ConfigurationErrorsException' occurred in System.Configuration.dll but was not handled in user code System.Configuration.dll中发生类型'System.Configuration.ConfigurationErrorsException'的异常,但未在用户代码中处理

Additional information: A configuration file cannot be created for the requested Configuration object. 附加信息:无法为请求的Configuration对象创建配置文件。

正如Dbugger在评论中提到的,解决方案是

WebConfigurationManager.OpenWebConfiguration("~"); –  dbugger

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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