web.config转换中添加Location授权重复生成问题求助
Web.Config转换避免重复Location节点的解决方法
问题根源
使用SetAttributes(path)生成Location节点时,该方法会为每个匹配的子元素创建一个Location实例,因此出现重复节点。
正确实现方式
直接在配置转换文件的根级别添加单个Location节点,而非在子节点上应用SetAttributes,具体代码如下:
方式1:插入新的Location节点(无原有节点时)
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"> <location path="AjaxFileUploadHandler.axd" xdt:Transform="Insert"> <system.web> <authorization> <allow users="*" /> </authorization> </system.web> </location> </configuration>
方式2:替换原有同名Location节点(有原有节点时)
如果目标web.config中已存在path="AjaxFileUploadHandler.axd"的Location节点,用以下代码替换,避免重复:
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"> <location path="AjaxFileUploadHandler.axd" xdt:Transform="Replace" xdt:Locator="Match(path)"> <system.web> <authorization> <allow users="*" /> </authorization> </system.web> </location> </configuration>
关键说明
xdt:Transform="Insert"仅会在配置根节点下插入一次该Location节点,不会生成重复项。xdt:Locator="Match(path)"用于精准定位到指定path的Location节点,配合Replace可覆盖原有配置,确保只保留一个目标节点。- 避免在
system.web/authorization这类子节点上使用SetAttributes生成Location,这是触发重复节点的核心原因。
内容的提问来源于stack exchange,提问作者L. Wallach
相关产品推荐
相关产品推荐

