2015-05-06 24 views
0

我想使用powershell腳本將以下內容添加到我的web.config中。需要將Access-Control-Allow- *標題添加到web.config

<system.webServer> 
    <httpProtocol> 
    <customHeaders> 
     <clear /> 
     <add name="Access-Control-Allow-Origin" value="*" /> 
     <add name="Access-Control-Allow-Headers" value="Content-Type" /> 
     <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" /> 
    </customHeaders> 
    </httpProtocol> 

這裏是PowerShell的代碼片段,我已(只包括頂層1,其他兩個看起來一樣)

Write-Host "Importing WebAdministration" 
Import-Module WebAdministration 
cd IIS:\ 

$sitePath = ("IIS:\Sites\test.test1.com") 

Write-Host "This works" 
Set-WebConfigurationProperty system.web/sessionState $sitePath -Name mode -  Value Off 

Write-Host "Does not work" 
Set-WebConfigurationProperty -PSPath $sitePath -Filter 'system.webServer/httpProtocol/customHeaders/add[@name="Access-Control-Allow-Origin"]' -Name 'value' -Value '*' -Force 

當這樣執行我得到以下結果在章魚。

警告:目標配置對象 「system.webServer/httpProtocol/customHeaders /訪問控制允許來源不是 在路徑發現 'MACHINE/WEBROOT/APPHOST/sub.mysite.com'。

該值未被添加。我導入了Web管理模塊,其他大多數設置都可以使用。

回答

0

我認爲您的XPath表達式與您嘗試操作的節點不匹配。試試這個:

Add-WebConfigurationProperty -PSPath $sitePath ` 
    -Filter 'system.webServer/httpProtocol/customHeaders/add[@name="Access-Control-Allow-Origin"]' ` 
    -Name 'value' -Value '*' -Force 
+0

嗨,試過這個,沒有再收到警告,但該屬性仍然沒有在web.config中設置。 – Captain0

0

用下面的方法對它進行整理。

Add-WebConfigurationProperty //system.webServer/httpProtocol/customHeaders "IIS:\sites\test.test1.com" -AtIndex 0 -Name collection -Value @{name='Access-Control-Allow-Origin';value='*'} 
Add-WebConfigurationProperty //system.webServer/httpProtocol/customHeaders "IIS:\sites\test.test1.com" -AtIndex 0 -Name collection -Value @{name='Access-Control-Allow-Headers';value='Content-Type'} 
Add-WebConfigurationProperty //system.webServer/httpProtocol/customHeaders "IIS:\sites\test.test1.com" -AtIndex 0 -Name collection -Value @{name='Access-Control-Allow-Methods';value='GET, OPTIONS'} 

希望這可以幫助別人在未來,浪費在這個分配的時間。