我在进行配置转换、添加nuget包安装时的应用设置方面遇到了问题,其中元素appSetting
可能存在,也可能不存在。
我想要发生的事情:
appSetting
元素不存在- 插入
appSetting
元素及其子元素
- 插入
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
元素已经存在,我希望它仍然评估其子元素并在不存在时插入这些元素,但似乎它们只是被忽略了。是否有其他值可以用于属性xdt:Transform
,或者有其他方法可以解决这个问题?
web.config.transform
。不过它似乎会插入重复的条目,所以如果这个方法行得通的话,我就改用这种方式了。 :) - furier