Практическое руководство. Доступ к параметрам конфигурации ASP.NET программными средствами

Обновлен: Ноябрь 2007

Для доступа к параметрам конфигурации во время выполнения можно использовать приложение ASP.NET или клиентское приложение .NET. Каждый раздел конфигурации обладает собственным типом объектов, который в случае использования C# требует приведения при вызове методов класса WebConfigurationManager. Дополнительные сведения о типа объектов, связанных с разделом конфигурации, см. обработчик раздела в таблице сведений об элементах в справочных разделах Параметры конфигурации ASP.NET.

В примере кода в этом разделе используется нестатический метод получения данных конфигурации. Это позволяет получать сведения о конфигурации из любого приложения. Для получения сведений о конфигурации из приложения, в котором располагается код, лучше использовать статические методы GetSection, которые работают быстрее. Дополнительные сведения см. в разделе «Работа с локальными и удаленными параметрами конфигурации» в разделе Общие сведения о конфигурационном API ASP.NET.

Пример

В следующем примере кода считывается значение атрибута impersonate элемента identity, сконфигурированного для приложения MyAppRoot. Значение отображается на веб-странице. Код использует тип объекта IdentitySection для чтения данных в разделе identity.

Для изменения параметра конфигурации используйте метод Save или SaveAs объекта конфигурации. Дополнительные сведения см. в разделе Использование классов конфигурации.

<%@ Page Language="VB" %>

<%@ Import Namespace="System.Web.Configuration" %>
<%@ Import Namespace="System.Configuration" %>
<%@ Import Namespace="System.Text" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

        ' Set the root path of the Web application that contains the
        ' Web.config file that you want to access.
        Dim configPath As String = "/MyAppRoot"

        ' Get the configuration object to access the related Web.config file.
        Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration(configPath)

        ' Get the object related to the <identity> section.
        Dim section As New IdentitySection
        section = config.GetSection("system.web/identity")

        ' Read the <identity> section.
        Dim identity As New StringBuilder
        identity.Append("Impersonate: ")
        identity.Append(section.Impersonate.ToString())

        ' Display the <identity> information.
        ConfigId.Text = identity.ToString()

    End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Read Configuration Settings</title>
</head>
<body>
    <h2>
        Read ASP.NET Configuration</h2>
    <p>
        This page displays the value of the <b>Impersonate</b> attribute of the <b>identity</b>
        section of an ASP.NET configuration.
    </p>
    <h3>
        Results</h3>
    <p>
        <asp:Label ID="ConfigId" BackColor="#dcdcdc" BorderWidth="1" runat="Server" /></p>
</body>
</html>
<%@ Page Language="C#" %>

<%@ Import Namespace="System.Web.Configuration" %>
<%@ Import Namespace="System.Configuration" %>
<%@ Import Namespace="System.Text" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script language="C#" runat="server">
    public void Page_Load()
    {
        try
        {
            // Set the root path of the Web application that contains the
            // Web.config file that you want to access.
            string configPath = "/MyAppRoot";

            // Get the configuration object to access the related Web.config file.
            Configuration config = WebConfigurationManager.OpenWebConfiguration(configPath);

            // Get the object related to the <identity> section.
            IdentitySection section =
              (IdentitySection)config.GetSection("system.web/identity");

            // Read the <identity> section.
            StringBuilder identity = new StringBuilder();
            identity.Append("Impersonate: ");
            identity.Append(section.Impersonate.ToString());

            // Display the <identity> information.
            ConfigId.Text = identity.ToString();
        }
        catch (Exception e)
        {
            ConfigId.Text = e.ToString();
        }
    }
  </script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Read Configuration Settings</title>
</head>
<body>
    <h2>
        Read ASP.NET Configuration</h2>
    <p>
        This page displays the value of the <b>Impersonate</b> attribute of the <b>identity</b>
        section of an ASP.NET configuration.
    </p>
    <h3>
        Results</h3>
    <p>
        <asp:Label ID="ConfigId" BackColor="#dcdcdc" BorderWidth="1" runat="Server" /></p>
</body>
</html>

См. также

Основные понятия

Использование классов конфигурации

Общие сведения о конфигурационном ASP.NET

Ссылки

OpenWebConfiguration

Другие ресурсы

Настройка приложений

How-to Topics — Configuring ASP.NET Applications