8

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

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

4

1 回答 1

13

听起来您希望更改站点的 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。

然后这将禁用该站点的匿名身份验证;然后为站点启用基本和 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();
}

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

希望对您有所帮助,这些示例来自此处

于 2012-12-13T00:17:01.567 回答