How to programmatically set App Pool Identity on IIS 8

做~自己de王妃 提交于 2019-12-08 08:49:32

问题


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.


回答1:


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;



回答2:


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:



来源:https://stackoverflow.com/questions/27116530/how-to-programmatically-set-app-pool-identity-on-iis-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!