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

时间:2012-03-29 13:47:29

标签: c# .net iis-7 servermanager

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

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

1 个答案:

答案 0 :(得分:11)

听起来您希望改变网站的Internet信息系统配置;如果这是正确的,这样的事情应该有效:

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。

然后这将禁用该站点的匿名身份验证;然后启用Basic&该站点的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"] = @"P@ssw0rd";
    addElement["enabled"] = true;
    credentialsCollection.Add(addElement);

    serverManager.CommitChanges();
}

互联网信息系统有很多灵活性;它非常强大。通过那里参考的文件也非常深入。这些示例很难适应您的特定用法,或者至少提供一定程度的理解,以使其按照您的意愿行事。

希望有帮助,这些例子来自here

相关问题