March 1, 2010

如何使IIS顯示自訂組態區段

開發及測試環境: Windows 7 Enterprise & Windows 2008 Server R2 Enterprise, IIS 7

習慣上我們常會直接修改Web.config檔來變更網站的設定資料。如果要透過IIS的管理介面來修改的話,可以使用它提供的「設定編輯器」來針對網站設定做變更,變更後的設定將寫回Web.config。

但點進了「設定編輯器」,卻發現自訂組態區段沒出現在上頭,也找不到可以新增自訂組態區段的地方。

研究了一下發現,IIS將其組態區段設定放置C:\Windows\System32\inetsrv\config\schema路徑下,我們可以看到在此資料夾下有幾個XML檔案。
而欲顯示自訂組態,需先有一份描述自訂組態的綱要檔存放在C:\Windows\System32\inetsrv\config\schema,如下(也可參考其它綱要檔的撰寫方式)。
<?xml version="1.0" encoding="utf-8"?>
<configSchema>
  <sectionSchema name="MailSetting">
    <attribute name="SmtpHost" type="string"></attribute>
    <attribute name="SmtpPort" type="int" defaultValue="25" />
    <attribute name="UseSsl" type="bool" defaultValue="false"></attribute>
    <attribute name="UseHtml" type="bool" defaultValue="true"></attribute>
    <attribute name="Sender" type="string"></attribute>
    <attribute name="SenderDisplayName" type="string"></attribute>
    <attribute name="UserName" type="string"></attribute>
    <attribute name="Password" type="string"></attribute>
  </sectionSchema>
</configSchema>

寫好自訂組態的網要檔後,再到C:\Windows\System32\inetsrv\config下修改applicationHost.config檔案,在<configuration>下<configSections>中加入如下XML片段
<section name="MailSetting" overrideModeDefault="Allow" allowDefinition="Everywhere" />
如此,即可在IIS中看到自訂組態區段了。


備註
1.經以上設定後,勿在Web.config再設定相同的自訂組態區段,否則將會出現重複定義區段的錯誤訊息


參考資料
http://mvolo.com/blogs/serverside/archive/2007/08/04/IISSCHEMA.EXE-_2D00_-A-tool-to-register-IIS7-configuration-sections.aspx
http://www.leastprivilege.com/InstallingAnIIS7Extension.aspx
http://learn.iis.net/page.aspx/242/extending-iis7-schema-and-accessing-the-custom-sections-using-mwa/