使用ServerManager类配置IIS身份验证设置

问题描述:

我正在使用ServerManager类(来自Microsoft.Web.Administration)在运行IIS 7的服务器上创建应用程序。我想配置应用程序是使用匿名身份验证还是Windows身份验证在应用程序的基础上,所以我不能简单地要求IT更改根站点上的设置。该应用程序的内容属于第三方,所以我不允许更改应用程序内部的web.config文件。使用ServerManager类配置IIS身份验证设置

Application类没有公开任何有用的属性,但也许我可以使用ServerManager的GetApplicationHostConfiguration方法完成某些操作?

这听起来像你希望改变网站的互联网信息系统配置;如果这是正确的这样的事情应该工作:

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