You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用IISAdministration模块创建指定IIS站点配置段?

使用IISAdministration模块创建IIS自定义缓存头配置

要在applicationHost.config中生成如下配置段:

<location path="MyWebSite/js">
    <system.webServer>
        <httpProtocol>
            <customHeaders>
                <add name="Cache-Control" value="private,max-age=28800" />
            </customHeaders>
        </httpProtocol>
    </system.webServer>
</location>

可以通过以下IISAdministration模块的PowerShell代码实现:

# 获取IIS服务器管理器实例
$manager = Get-IISServerManager
# 获取目标路径的Web配置
$config = $manager.GetWebConfiguration("MyWebSite/js")
# 定位到customHeaders集合
$headersSection = $config.GetSection("system.webServer/httpProtocol")
$headersCollection = $headersSection.GetCollection("customHeaders")

# 检查是否已存在同名的Cache-Control头
$existingHeader = $headersCollection | Where-Object { $_.GetAttributeValue("name") -eq "Cache-Control" }

if (-not $existingHeader) {
    # 创建新的头元素
    $newHeader = $headersCollection.CreateElement("add")
    $newHeader.SetAttributeValue("name", "Cache-Control")
    $newHeader.SetAttributeValue("value", "private,max-age=28800")
    # 将新元素添加到集合
    $headersCollection.Add($newHeader)
    # 提交配置更改
    $manager.CommitChanges()
}

代码说明

  • 先通过Get-IISServerManager获取管理器实例,再定位到目标站点路径的配置节点
  • 找到customHeaders集合后,先检查目标头是否已存在,避免重复添加
  • 若不存在则创建新的add元素,设置对应的name和value属性,添加到集合后提交更改

你之前用来访问该配置的代码可以正常用来验证配置是否创建成功:

$manager = Get-IISServerManager
$config = $manager.GetWebConfiguration("MyWebSite/js")
$headers = $config.GetSection("system.webServer/httpProtocol").GetCollection("customHeaders")

内容的提问来源于stack exchange,提问作者Zergatul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 15:03:33