有許多方式利用這種和APPCMD
C#/ VB.NET/JavaScript的/ VBScript中做:
Custom Headers (IIS.NET)
要做到這一點使用PowerShell和Microsoft.Web.Administration
裝配:
[Reflection.Assembly]::Load("Microsoft.Web.Administration, Version=7.0.0.0, Culture=Neutral, PublicKeyToken=31bf3856ad364e35")
$serverManager = new-object Microsoft.Web.Administration.ServerManager
$siteConfig = $serverManager.GetApplicationHostConfiguration()
$httpProtocolSection = $siteConfig.GetSection("system.webServer/httpProtocol", "Default Web Site")
$customHeadersCollection = $httpProtocolSection.GetCollection("customHeaders")
$addElement = $customHeadersCollection.CreateElement("add")
$addElement["name"] = "X-Custom-Name"
$addElement["value"] = "MyCustomValue"
$customHeadersCollection.Add($addElement)
$serverManager.CommitChanges()
這將導致<location>
路徑applicationHost.config
下列要求:
<location path="Default Web Site">
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="X-Custom-Name" value="MyCustomValue" />
</customHeaders>
</httpProtocol>
</system.webServer>
</location>
要使用新的IIS 7 PowerShell Snap-In這樣做在PowerShell中:
add-webconfiguration `
-filter /system.webServer/httpProtocol/customHeaders `
-location "Default Web Site" `
-pspath "IIS:" `
-value @{name='X-MyHeader';value='MyCustomHeaderValue'} `
-atindex 0
這將配置一個<location>
路徑applicationHost.config
與下列:
<location path="Default Web Site">
<system.webServer>
<httpProtocol>
<customHeaders>
<clear />
<add name="X-MyHeader" value="MyCustomHeaderValue" />
<add name="X-Powered-By" value="ASP.NET" />
</customHeaders>
</httpProtocol>
</system.webServer>
</location>
背蜱在每一行的末尾指示線延續。上面給出的兩個示例在Windows 2008 Server SP2上進行了測試。
來源
2009-11-11 17:59:20
Kev
這是預期的行爲 - IIS 6管理兼容性的重點在於允許您使用IIS 6腳本管理IIS 7。 – 2009-11-11 18:44:59
但是,我同意使用MWA名稱空間或PS管理單元更好。通過System.DirectoryServices使用ADSI可以解決applicationHost.config文件的問題。例如,在操作腳本映射時會創建AboCustomerMapper對象。這些可能會導致長期頭痛。 – Kev 2009-11-11 18:57:09