如何以编程方式设置应用程序池标识

时间:2014-11-25 00:05:45

标签: c# .net iis iis-8 application-pool

我正在运行带有IIS 8的Windows Server 2012.我安装了iis 6配置数据库兼容性。我一直试图用.Net 4.5来解决如何更改IIS 8的应用程序池标识。我发现的所有示例都是针对IIS 6和7的。

这就是我所拥有的:

public class InternetInformationServices
{
    public void SetApplicationPoolIdentity(string appPoolName, string domain, string username, string password)
    {
        try
        {
            string metabasePath = "IIS://Localhost/W3SVC/AppPools";

            DirectoryEntry myAppPool;
            DirectoryEntry apppools = new DirectoryEntry(metabasePath);
            myAppPool = apppools.Children.Find(appPoolName, "IIsApplicationPool");
            myAppPool.Invoke("AppPoolIdentityType", new Object[] { 3 });
            myAppPool.Invoke("WAMUserName", new Object[] { domain + @"\" + username });
            myAppPool.Invoke("WAMUserPass", new Object[] { password });
            myAppPool.Invoke("SetInfo", null);
            myAppPool.CommitChanges();
        }
        catch (Exception)
        {
            throw;
        }
    }
}

代码能够找到应用程序池,但是一旦我去调用以设置以下任何内容:

 myAppPool.Invoke("AppPoolIdentityType", new Object[] { 3 });
 myAppPool.Invoke("WAMUserName", new Object[] { domain + @"\" + username });
 myAppPool.Invoke("WAMUserPass", new Object[] { password });

我在内部异常上收到以下错误:

 Value does not fall within the expected range.

所以我不确定我缺少什么或与IIS 8有什么不​​同。

2 个答案:

答案 0 :(得分:2)

这是一种在iis元数据库中为大多数内容获取此类代码段的方法。我们使用这个过程在我的办公室编写脚本自动化脚本。

我将使用您关于指定凭据的问题作为示例:

首先打开inetmgr,然后选择您的主机名,然后打开配置。 enter image description here

然后选择system.applicationHost / applicationPools config部分并展开app pools集合,完成后退出窗口: enter image description here 选择适当的应用程序池,将identitytype更改为特定用户并设置用户并传递。enter image description here

现在点击生成脚本,不要应用更改。enter image description here

最后:您想要的所有api善良,包括您的示例代码:enter image description here

答案 1 :(得分:1)

试试这个(来自How can I change the username/password of an ApplicationPool in IIS from C#?

myAppPool .Properties["AppPoolIdentityType"].Value = 3;
myAppPool .Properties["WAMUserName"].Value = Environment.MachineName + @"\" + username;
myAppPool .Properties["WAMUserPass"].Value = password;