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

前端之家收集整理的这篇文章主要介绍了c# – 使用ServerManager类配置IIS身份验证设置前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用ServerManager类(来自Microsoft.Web.Administration)在运行IIS 7的服务器上创建应用程序.我想配置应用程序是否在应用程序基础上使用匿名身份验证或 Windows身份验证,因此我不能简单地要求IT更改根站点上的设置.该应用程序的内容属于第三方,因此我不允许更改应用程序内的web.config文件.

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.

然后,这将禁用该站点的匿名身份验证;然后启用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

猜你在找的C#相关文章