.net - Web.config 转换添加树

标签 .net asp.net-mvc web-config webmatrix web.config-transform

我想在发布时将以下内容添加到 Web 配置中:

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="Strict-Transport-Security" value="max-age=16070400; includeSubDomains" xdt:Transform="Insert" />
        </customHeaders>
    </httpProtocol>
</system.webServer>

默认 Web 配置中没有任何自定义 header ,因此我在发布时收到错误:源文档中没有元素与 '/configuration/system.webServer/httpProtocol/customHeaders' 匹配 .

我只需将空元素添加到 web.config 即可解决此问题,如下所示:

  <httpProtocol>
    <customHeaders>
    </customHeaders>
  </httpProtocol>

但是,感觉这不是正确的方式。

是否有更正确的方法来在变换上构建元素树?

最佳答案

添加空<customHeaders> web.config 的节点有效,因为您所进行的转换是插入 <add .../>节点,而不是 <customHeaders>节点。它只能插入与该点匹配的位置。

要插入节点树,请移动 xdt:Transform="Insert"在 XML 中稍微增加一点。如果您从 web.config 开始:

<?xml version="1.0">
<configuration>
  <system.webServer>
    <httpProtocol />
  </system.webServer>
</configuration>

并将其转换为:

<?xml version="1.0">
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <system.webServer>
    <httpProtocol>
      <customHeaders xdt:Transform="Insert">
        <add name="Strict-Transport-Security" value="max-age=16070400; includeSubDomains" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration>

你最终会得到:

<?xml version="1.0">
<configuration>
  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Strict-Transport-Security" value="max-age=16070400; includeSubDomains" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration>

这是一个有用的 web.config transformation tester .

关于.net - Web.config 转换添加树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32936953/

相关文章:

asp.net-mvc - ASPNET HttpErrors 重定向到 Controller

web-config - web.config 将多个域重定向到一个域

iis - 异常消息 : WebSockets is unsupported in the current application configuration

c# - protobuf-net 代码生成器

c# - 使用 Autofac 将 log4net 注入(inject) Controller

c# - Telerik Ajax UpdatePanel radgrid 等待页面加载

c# - 如何在 ASP.NET MVC 中跳过表单例份验证到某些 Controller 操作

asp.net-mvc - 在 ASP.NET MVC 中将 DateTime 拆分为日期和时间

.net - .NET 的内部工作原理——内置设置加载器可以通过代码访问吗?

c# - 剥离后如何从网络上获取图像文件扩展名?