Cómo: Tener acceso a las opciones de configuración de ASP.NET mediante programación

Actualización: noviembre 2007

Es posible tener acceso a los valores de configuración en tiempo de ejecución desde una aplicación ASP.NET o una aplicación cliente .NET. Cada sección de configuración tiene su propio tipo de objeto, que, en el caso de C#, precisa de conversión al llamar a los métodos de la clase WebConfigurationManager. Para obtener más información sobre el tipo de objeto asociado a una sección de configuración, vea el controlador de sección en la tabla Información de elementos de los temas de referencia de Opciones de configuración de ASP.NET.

En el ejemplo de código de este tema se utiliza el método no estático para obtener datos de configuración. Esto permite obtener información sobre la configuración desde cualquier aplicación. Si va a obtener información de configuración de la aplicación en la que reside el código, utilice los métodos estáticos GetSection que procesan con más rapidez. Para obtener más información, vea la sección Trabajar con valores de configuración local y remota en Información general sobre la API de configuración de ASP.NET.

Ejemplo

En el ejemplo de código siguiente se lee el valor del atributo impersonate del elemento identity configurado para la aplicación MyAppRoot. El valor se muestra en la página Web. El código utiliza el tipo de objeto IdentitySection para leer los datos de la sección identity.

Para cambiar un valor de configuración, utilice el método Save o SaveAs del objeto de configuración. Para obtener más información, vea Utilizar las clases Configuration.

<%@ 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 >

    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#" >
    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>

Vea también

Conceptos

Utilizar las clases Configuration

Información general sobre la configuración de ASP.NET

Referencia

OpenWebConfiguration

Otros recursos

Configurar aplicaciones

Temas "Cómo...": configurar aplicaciones ASP.NET