覆盖从machine.config到web.config的键

时间:2013-12-17 21:18:43

标签: asp.net

我需要将一个密钥从machine.config移动到web.config。以下是machine.config中的设置。

<commonsettings>
    <setting environment="dev">
      <common>
          <value1>myValue1</value1>
          <value2>myValue2</value2>
          <value3>myValue3</value3>
      </common>
    </setting>
</commonsettings>

我目前在machine.config中定义了上面提到的设置(3个键 - value1,value2,value3),我想在web.config中只声明value1。

我只声明了value1设置,但它不起作用。 secion只识别value1。我无法访问machine.config

中声明的value2和value3

以下是我在web.config中所做的。

<commonsettings>
    <setting environment="dev">
      <common>
          <value1>myValue1</value1>
      </common>
    </setting>
</commonsettings>

我想要的是web.config执行一些继承而不是覆盖整个部分。

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

您可以在代码中执行此操作 我假设你在machine.config中定义了处理程序的类型:

<configuration>
  <configSections>
      <section name="commonsettings" type="YourConfigSectionHandler, YourLibrary, Version=1.1.0.0"/>
 </configSections>
<!-- More configuration-->
<configuration>

在您的应用内创建该类型的类:

public class YourSectionHandler : IConfigurationSectionHandler
{
    public object Create( object parent, object configContext, XmlNode section )
    {
        //your code to handler the configSection
    }
}

如果您看到Create方法有一个参数object parent。它将包含父配置的配置。

我认为你只有一台machine.config和一个web.config。

  1. 应用启动后,会尝试解析machine.config/configSection/commonsettings/(应在此处声明部分),Create方法将通过null父级调用。
  2. 稍后您的应用配置将被解析,Create方法将再次被调用。现在,parent object参数将保存上一步解析结果的值。