配置文件 XDT 转换 InsertIfMissing 正在跳过 children

Config file XDT transformation InsertIfMissing is skipping children

我在进行配置转换时遇到问题,在 nuget 包安装上添加应用程序设置时元素 appSetting 可能存在也可能不存在。

我想要发生的事情:

我只能让其中一个工作,但不能同时工作。

web.config.install.xdt

<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <appSettings xdt:Transform="InsertIfMissing" >
    <add key="Swagger.Contact.Name" value="Some Name" xdt:Transform="InsertIfMissing" />
    <add key="Swagger.Contact.Email" value="some@email.address" xdt:Transform="InsertIfMissing" />
  </appSettings>
</configuration>

示例 1

web.config之前

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" maxRequestLength="51200" />
    <customErrors mode="Off" />
  </system.web>
</configuration>

appSettings 元素 转换前不存在

web.config 之后

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" maxRequestLength="51200" />
    <customErrors mode="Off" />
  </system.web>
  <appSettings>
    <add key="Swagger.Contact.Name" value="Some Name" />
    <add key="Swagger.Contact.Email" value="some@email.address" />
  </appSettings>
</configuration>

示例 2

web.config之前

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" maxRequestLength="51200" />
    <customErrors mode="Off" />
  </system.web>
  <appSettings>
    <add key="Other.Key" value="With Some Value" />
  </appSettings>
</configuration>

appSettings元素存在转换前

web.config 之后

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" maxRequestLength="51200" />
    <customErrors mode="Off" />
  </system.web>
  <appSettings>
    <add key="Other.Key" value="With Some Value" />
  </appSettings>
</configuration>

示例 2 中没有任何反应,因为 appSettings 元素已经存在,我希望它仍然评估其 child 元素并在它们不存在时插入它们,但看起来它们只是忽略。我可以使用属性 xdt:Transform 的任何其他值,或任何其他技巧来解决此问题?

很久以前我遇到过类似的问题。我应用的解决方法是在 XDT 文件中有两个带有 <appSettings> 的条目,一个检查它是否不存在,如果是,则继续并插入它。另一个是针对 <appSettings> 元素已经存在的情况。这是帮助您解决问题的简短片段:

<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
    <appSettings xdt:Transform="InsertIfMissing">
    </appSettings>
    <appSettings>
      <add key="Swagger.Contact.Name" value="Some Name" xdt:Transform="InsertIfMissing" />
      <add key="Swagger.Contact.Email" value="some@email.address" xdt:Transform="InsertIfMissing" />
    </appSettings>
</configuration>

让我知道这是否适合你。