C# - Ошибка раздела конфигурации не найдена при использовании aspnet_regiis.exe

Я пытаюсь зашифровать конфиденциальную информацию о строке подключения в моем файле app.config для приложения С#, которое я разрабатываю. Я использую следующую команду из командной строки VS, работающей от имени администратора:

aspnet_regiis.exe -pef "Credentials" "C:\Users\.....\MyProjectFolderDir"

Это структура моего файла app.config:

<?xml version="1.0" encoding="utf-8" ?>
<config>
    <configSections>
      <section name="ApplicationSettings" type="sometype"/>
      <section name="WebSettings" type="sometype"/>
      <section name="Credentials" type="sometype"/>
      <section name="SQLServerSettings" type="sometype"/>
    </configSections>

    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>

    <ApplicationSettings   Mode="mymode"
                           FileSearchMode="myfilemode"
                           SubtractHoursDebugging="0"/>

    <WebSettings WebApiServers=""
                    CredentialMethod="mymethod"/>

    <Credentials
                    Domain="mydomain"
                    UserName="myusername"
                    Password="mypassword"/>

    <SQLServerSettings
        ConnectionString="Server=***********"/>

  </config>

Однако я продолжаю получать следующую ошибку:

Раздел конфигурации шифрования... Раздел конфигурации «Учетные данные» не найден. Не удалось!

Как я могу заставить это зашифровать мой раздел?


person Hooplator15    schedule 14.07.2016    source источник
comment
Вы пытались использовать config/Credentials? Возможно, вам придется углубиться еще больше.   -  person Ju66ernaut    schedule 14.07.2016
comment
Разве ваш файл app.config не должен начинаться с ‹configuration›, а не ‹config›? Итак, начало файла должно быть ‹?xml version=1.0 encoding=utf-8 ?› ‹configuration›   -  person Jon    schedule 14.07.2016
comment
Ну, технически да, но у меня были проблемы со схемой, в которой говорилось что-то о влиянии "configuration is declared twice", поэтому я просто переименовал ее в config.   -  person Hooplator15    schedule 14.07.2016
comment
Это приложение WinForms? Потому что веб-приложение должно иметь файл web.config.   -  person dbugger    schedule 15.07.2016
comment
Это не приложение winforms, это консольное приложение.   -  person Hooplator15    schedule 15.07.2016


Ответы (3)


Ваш файл конфигурации должен начинаться с элемента <configuration>, а не с <config>. Поскольку это <config> aspnet_regiis.exe истончение Credentials как вложенного элемента и, следовательно, ошибка. С вашим текущим файлом конфигурации команда должна быть

aspnet_regiis.exe -pef "config\Credentials" "C:\Users\.....\MyProjectFolderDir"
person Rahul    schedule 14.07.2016
comment
Я пробовал это, и это все еще не работает. Может кто попробует на своей машине? - person Hooplator15; 14.07.2016
comment
C:\Windows\Microsoft.NET\Framework\v2.0.50727›aspnet_regiis.exe -pef config/Credentials C:\Users\Me\Desktop Раздел конфигурации шифрования... Раздел конфигурации 'config/Credentials' не найден. Не удалось! - person Hooplator15; 14.07.2016

Прежде всего, вот ответ, который вы можете узнать из раздела пользовательской конфигурации Как создать пользовательский раздел конфигурации в app.config? и вот пример из msdn https://msdn.microsoft.com/en-us/library/2tw134k3.aspx

Во-вторых, тип обычно относится к реальной модели, поэтому вы должны ввести пространство имен и класс, которые вы создали для моделирования типа конфигурации, которую вы хотели бы использовать, следующим образом:

 <configuration>
 <configSections>
  <section name="sampleSection"
           type="System.Configuration.SingleTagSectionHandler" />
</configSections>
<sampleSection setting1="Value1" setting2="value two" 
              setting3="third value" />
</configuration>

Надеюсь, поможет

person Erez.L    schedule 14.07.2016

Как оказалось, aspnet-regiis.exe предназначен исключительно для файлов web.config. Он не работает с файлами app.config, если вы не переименуете их в web.config. Вместо того, чтобы переименовывать мой app.config каждый раз, когда я хотел зашифровать/расшифровать, я создал класс, который будет обрабатывать это каждый раз, когда я запускаю приложение. Убедитесь, что вы используете следующее:

using System.Configuration;
using System.Web.Security;

Сорт:

internal class Crypto
{
    internal static AppSettingsSection GetEncryptedAppSettingsSection(string exeConfigName)
    {
        // Open the configuration file and retrieve 
        // the connectionStrings section.
        System.Configuration.Configuration config = ConfigurationManager.
            OpenExeConfiguration(exeConfigName);

        AppSettingsSection section =
                config.GetSection("appSettings")
                as AppSettingsSection;

        EncryptConfigSection(config, section);
        return section;
    }

    internal static ConnectionStringsSection GetEncryptedConnectionStringsSection(string exeConfigName)
    {
        // Open the configuration file and retrieve 
        // the connectionStrings section.
        System.Configuration.Configuration config = ConfigurationManager.
            OpenExeConfiguration(exeConfigName);

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

        EncryptConfigSection(config, section);
        return section;
    }

    internal static void EncryptConfigSection(System.Configuration.Configuration config, ConfigurationSection section)
    {
        //Ensure config sections are always encrypted
        if (!section.SectionInformation.IsProtected)
        {
            // Encrypt the section.
            section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
            // Save the current configuration.
            config.Save();
        }
    }
}
person Hooplator15    schedule 22.07.2016