How to programmatically set App Pool Identity on I

2019-06-05 12:49发布

I'm running Windows Server 2012 with IIS 8. I have IIS 6 Metabase Compatibility installed. I have been trying to figure out how to change the App Pool Identity for IIS 8 with .Net 4.5 - all of the examples I found are for IIS 6 and 7.

Here is what I have:

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;
        }
    }
}

The code is able to find the App Pool, but as soon as I invoke it to set any of the following:

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

I get the following error on the inner exception:

Value does not fall within the expected range.

I'm not sure what I'm missing, or what is different with IIS 8.

2条回答
\"骚年 ilove
2楼-- · 2019-06-05 13:09

Try this ( from 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;
查看更多
别忘想泡老子
3楼-- · 2019-06-05 13:29

Here's a way to get this type of code snippet for most things in the iis metabase. we use this process to script automation at my office.

I'll use your question about specifying credentials as an example:

open inetmgr first and then select your hostname and then open the config. enter image description here

then select the system.applicationHost/applicationPools config section and expand the app pools collection, when done exit the window: enter image description here select the appropriate application pool, change the identitytype to specific user and set the user and pass.enter image description here

Now click on Generate script, do not apply changes.enter image description here

FINALLY: All the api goodness you wanted, including your sample code: enter image description here

查看更多
登录 后发表回答