簡體   English   中英

加密連接字符串:“此操作在運行時不適用”

[英]Encrypting connection string: “This operation does not apply at runtime”

我有一個控制台應用程序,它有app.config。 當我運行此代碼時:

 class Program
    {
        static void Main()
        {

            ConnectionStringsSection connSection = ConfigurationManager.GetSection("connectionStrings") as 
                                                    ConnectionStringsSection;
            if (connSection != null)
            {
                if (!connSection.SectionInformation.IsProtected)
                    connSection.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");

                else
                    connSection.SectionInformation.UnprotectSection();
            }

            Console.Read();
        }
    }

我收到錯誤:“此操作在運行時不適用”。 我也試過給我的app.config權限,但沒有運氣。

有什么問題?

您可以嘗試以下方法:

 static void Main()
 {


     // Get the current configuration file.
     System.Configuration.Configuration config =
             ConfigurationManager.OpenExeConfiguration(
             ConfigurationUserLevel.None);

     ConnectionStringsSection connSection = config.GetSection("connectionStrings") as
                                             ConnectionStringsSection;

     if (connSection != null)
     {
         if (!connSection.SectionInformation.IsProtected)
             connSection.SectionInformation.ProtectSection(null);

         else
             connSection.SectionInformation.UnprotectSection();
     }

     connSection.SectionInformation.ForceSave = true;

     config.Save(ConfigurationSaveMode.Full);

     Console.ReadKey();
 }

我認為你應該在這種情況下使用OpenExeConfiguration方法:

  System.Configuration.Configuration config =
    ConfigurationManager.OpenExeConfiguration(pathToExecutable);

  ConnectionStringsSection connSection = 
    config .GetSection("connectionStrings") as ConnectionStringsSection;

參數pathToExecutable應該是應用程序的exe的完整路徑,例如:“C:\\ application \\ bin \\ myapp.exe”

您不應該在運行時加密部分,使用aspnet_setreg.exe工具在運行時加密它們。 更多信息在這里。

然后ASP.NET透明地在運行時讀取加密的部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM