通过外部文件更改配置的示例

更新:2007 年 11 月

可以使用外部配置文件扩展应用程序配置设置,并且可以通过启用或禁用应用程序重新启动功能控制在这些设置发生更改时是否保留状态信息。此功能由 restartOnExternalChanges 属性控制,该属性应用于不同的配置文件节。

示例 Web 应用程序文件

下面几小节包含用自定义节生成一个示例 Web 应用程序的代码,该自定义节的 configSource 属性指向一个外部配置文件,并且其 restartOnExternalChanges 属性最初设置为 true。

运行该 Web 应用程序将演示在对外部配置文件进行更改时全局回发计数器所发生的情况,所提供的代码示例演示在 restartOnExternalChanges 分别设置为 true、默认值和 false 时所发生的情况。

Global.asax

该示例 Web 应用程序必须包含此 Global.asax 页。下面的代码示例用一个全局回发计数器定义该页。该计数器通过刷新应用程序的 Default.aspx 页(在本主题后面定义)跟踪所生成的回发请求。

' Code that runs on application startup.
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs) 
    
    ' This counter is set to 0 the first time 
    ' the application starts and, thereafter, every 
    ' time it restarts.
    Dim postBackCount As Integer = 0
    
    Dim appState As HttpApplicationState = Application.Contents
    appState.Add("postBackKey", postBackCount)

End Sub 'Application_Start
// Code that runs on application startup.
void Application_Start(object sender, EventArgs e) 
{
       
        // This counter is set to 0 the first time 
        // the application starts and, thereafter, every 
        // time it restarts.
        int postBackCount = 0;
        
        HttpApplicationState appState = Application.Contents;
        appState.Add("postBackKey", postBackCount);
        
}

Default.aspx

Default.aspx 页包含在 Web.config 文件中创建自定义节、向 External.config 文件添加一个元素以及显示回发计数器值的代码。注意,该页必须包含一个 Label 控件以显示回发计数器的当前值。下面的代码示例演示定义此控件的一种可能方法。

<asp:Label ID="ResultId" runat="server" style="font-weight:bold; color:Red;"/>

下面的代码示例定义 Default.aspx 页。

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) 
        Dim extConfig As ExternalConfiguration = Nothing
        
        If Not IsPostBack Then
            ' Create an instance of the custom section.
            extConfig = New ExternalConfiguration()
        End If
                
        Dim postBackCount As Integer = _
        Fix(HttpContext.Current.Application("postBackKey"))
        'Display current counter value.
        ResultId.Text = postBackCount.ToString()
        
        HttpContext.Current.Application("postBackKey") = _
        Fix(HttpContext.Current.Application("postBackKey")) + 1
        
        extConfig.UpdateAppSettngs()
End Sub 'Page_Load
protected void Page_Load(object sender, EventArgs e)
{
        ExternalConfiguration extConfig = null;
        
        if (!IsPostBack)
        {
            // Create an instance of the cusom section.
            extConfig =
                new ExternalConfiguration();
        }

        int postBackCount =
           (int) HttpContext.Current.Application["postBackKey"];
        ResultId.Text = postBackCount.ToString();

        HttpContext.Current.Application["postBackKey"] =
            (int)HttpContext.Current.Application["postBackKey"] + 1;
 
        extConfig.UpdateAppSettngs();
}

Web.config

Web.config 文件定义 MyAppSettings 自定义节,如下面的代码示例所示。此示例使用标准类型处理此节,但您可以创建自己的类型。有关详细信息,请参见 ConfigurationElementConfigurationSection

<section 
    name="MyAppSettings" 
    type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" 
    restartOnExternalChanges="true" 
    requirePermission="false" />

External.config

External.config 文件包含 MyAppSettings 自定义节的详细信息。在首次运行应用程序之前,必须在应用程序根目录中手动创建此文件。有关更多信息,请参见节元素所继承的常规属性中的 configSource 属性。对于此示例,请确保您的代码包含下面的空节。

<MyAppSettings></ MyAppSettings>.

ExternalConfiguration.dll

ExternalConfiguration.dll 文件包含更新 MyAppSettings 自定义节的代码。可以将源代码放在应用程序的 App_Code 目录中。当请求您的应用程序时,ASP.NET 将对该示例进行编译。此外,还可以将该示例提供程序编译为库,并将其放在 Web 应用程序的 Bin 目录中。下面的代码示例演示如何从命令行编译该示例。

vbc /out: ExternalConfiguration.dll /t:library ExternalConfiguration.vb /r:System.Web.dll /r:System.Configuration.dll
csc /out: ExternalConfiguration.dll /t:library ExternalConfiguration.cs /r:System.Web.dll /r:System.Configuration.dll

下面的代码示例生成 ExternalConfiguration .dll 文件。

Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.Configuration
Imports System.Web.Configuration

Namespace Samples.AspNet


    Public Class ExternalConfiguration


        ' Instantiate the ExternalConfiguration type.
        Public Sub New()
            ' Access the root Web.config file.
            Dim config As System.Configuration.Configuration = _
            WebConfigurationManager.OpenWebConfiguration("/configTarget")

            ' Get the custom MyAppSettings section.
            Dim appSettings As AppSettingsSection = _
            CType(config.GetSection("MyAppSettings"), AppSettingsSection)

            ' Perform the first update.
            UpdateAppSettings()

        End Sub 'New



        ' Update the custom MyAppSettings section.
        ' Note , if the section restartOnExternalChanges attribute 
        ' is set to true, every update of the external 
        ' configuration file will cause the application 
        ' to restart.
        Public Sub UpdateAppSettings()

            Dim config As System.Configuration.Configuration = _
            WebConfigurationManager.OpenWebConfiguration("/configTarget")

            Dim appSettings As AppSettingsSection = _
            CType(config.GetSection("MyAppSettings"), AppSettingsSection)

            Dim count As Integer = appSettings.Settings.Count

            appSettings.Settings.Add("key_" + count.ToString(), _
            "value_" + count.ToString())

            config.Save()

        End Sub 'UpdateAppSettngs

    End Class 'ExternalConfiguration 

End Namespace
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Web.Configuration;

namespace Samples.AspNet
{


    public class ExternalConfiguration
    {

        // Instantiate the ExternalConfiguration type.
        public ExternalConfiguration()
        {
            // Access the root Web.config file.
            System.Configuration.Configuration config =
            WebConfigurationManager.OpenWebConfiguration(
                              "/configTarget");

            // Get the custom MyAppSettings section.
            AppSettingsSection appSettings =
                (AppSettingsSection)config.GetSection("MyAppSettings");

            // Perform the first update.
            UpdateAppSettings();
        }


        // Update the custom MyAppSettings section.
        // Note , if the section restartOnExternalChanges attribute 
        // is set to true, every update of the external 
        // configuration file will cause the application 
        // to restart.
        public void UpdateAppSettings()
        {

            System.Configuration.Configuration config =
            WebConfigurationManager.OpenWebConfiguration(
                              "/configTarget");

            AppSettingsSection appSettings =
                (AppSettingsSection)config.GetSection("MyAppSettings");

            int count = appSettings.Settings.Count;

            appSettings.Settings.Add(
                "key_" + count.ToString(), 
                "value_" + count.ToString());

            config.Save();
        }

    }
}

使用该示例 Web 应用程序

在首次运行该应用程序时,它将向 External.config 文件添加一些元素。

在每次刷新 Default.aspx 页时,回发计数器都会重置为零。这是因为 MyAppSettings 节中的 restartOnExternalChanges 属性默认设置为 true。

如果在 Web.config 文件中将 restartOnExternalChanges 属性设置为 false,您会发现每当刷新 Default.aspx 页时回发计数器就会递增,即使 External.config 文件中发生更改也是如此。这是因为已禁用了应用程序域重新启动。

请参见

任务

如何:使用 ConfigurationSection 创建自定义配置节

概念

管理对配置设置的更改

保证 ASP.NET 配置的安全

参考

ConfigurationElement

ConfigurationSection

节元素所继承的常规属性

位置

appSettings 元素(常规设置架构)

trace 元素(ASP.NET 设置架构)

HttpApplicationState