2012-03-29 47 views
6

我正在使用ServerManager類(來自Microsoft.Web.Administration)在運行IIS 7的服務器上創建應用程序。我想配置應用程序是使用匿名身份驗證還是Windows身份驗證在應用程序的基礎上,所以我不能簡單地要求IT更改根站點上的設置。該應用程序的內容屬於第三方,所以我不允許更改應用程序內部的web.config文件。使用ServerManager類配置IIS身份驗證設置

Application類沒有公開任何有用的屬性,但也許我可以使用ServerManager的GetApplicationHostConfiguration方法完成某些操作?

回答

9

這聽起來像你希望改變網站的互聯網信息系統配置;如果這是正確的這樣的事情應該工作:

using (ServerManager serverManager = new ServerManager()) 
{ 
    Configuration config = serverManager.GetWebConfiguration("Contoso"); 
    ConfigurationSection authorizationSection = config.GetSection("system.webServer/security/authorization"); 
    ConfigurationElementCollection authorizationCollection = authorizationSection.GetCollection(); 

    ConfigurationElement addElement = authorizationCollection.CreateElement("add"); 
    addElement["accessType"] = @"Allow"; 
    addElement["roles"] = @"administrators"; 
    authorizationCollection.Add(addElement); 

    serverManager.CommitChanges(); 
} 

上面的代碼將允許您創建一個授權規則,允許特定用戶組中訪問特定網站。在這種情況下,該網站是Contoso。

然後,這將禁用該網站的匿名身份驗證;然後啓用基本& Windows身份驗證的網站:

using(ServerManager serverManager = new ServerManager()) 
{ 
    Configuration config = serverManager.GetApplicationHostConfiguration(); 

    ConfigurationSection anonymousAuthenticationSection = config.GetSection("system.webServer/security/authentication/anonymousAuthentication", "Contoso"); 
    anonymousAuthenticationSection["enabled"] = false; 

    ConfigurationSection basicAuthenticationSection = config.GetSection("system.webServer/security/authentication/basicAuthentication", "Contoso"); 
    basicAuthenticationSection["enabled"] = true; 

    ConfigurationSection windowsAuthenticationSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication", "Contoso"); 
    windowsAuthenticationSection["enabled"] = true; 

    serverManager.CommitChanges(); 
} 

或者你可以簡單地添加IIS管理器用戶帳戶,如果你想;您可以將其設置爲某些權限來操作和管理這些其他應用程序。

using (ServerManager serverManager = new ServerManager()) 
{ 
    Configuration config = serverManager.GetAdministrationConfiguration(); 

    ConfigurationSection authenticationSection = config.GetSection("system.webServer/management/authentication"); 
    ConfigurationElementCollection credentialsCollection = authenticationSection.GetCollection("credentials"); 
    ConfigurationElement addElement = credentialsCollection.CreateElement("add"); 
    addElement["name"] = @"ContosoUser"; 
    addElement["password"] = @"[email protected]"; 
    addElement["enabled"] = true; 
    credentialsCollection.Add(addElement); 

    serverManager.CommitChanges(); 
} 

互聯網信息系統有很大的靈活性;它相當強大。通過這裏參考的文檔也相當深入。這些例子根本無法適應您的特定用法,或者至少提供一定程度的理解,使其達到您想要的效果。

希望有幫助,這些例子來自here