简体   繁体   中英

How to programmatically set App Pool Identity on IIS 8

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.

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. 在此处输入图片说明

then select the system.applicationHost/applicationPools config section and expand the app pools collection, when done exit the window: 在此处输入图片说明 select the appropriate application pool, change the identitytype to specific user and set the user and pass. 在此处输入图片说明

Now click on Generate script, do not apply changes. 在此处输入图片说明

FINALLY: All the api goodness you wanted, including your sample code: 在此处输入图片说明

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM