How can I change the username/password of an ApplicationPool in IIS from C#?

扶醉桌前 提交于 2020-01-10 04:34:24

问题


I am using the code below to create a new application pool in the Installer class of my application:

private static void CreateAppPool(string serverName, string appPoolName)
{
    //  metabasePath is of the form "IIS://<servername>/W3SVC/AppPools"
    //    for example "IIS://localhost/W3SVC/AppPools" 
    //  appPoolName is of the form "<name>", for example, "MyAppPool"
    string metabasePath = string.Format("IIS://{0}/W3SVC/AppPools", serverName);
    Console.WriteLine("\nCreating application pool named {0}/{1}:", metabasePath, appPoolName);
    try
    {
        DirectoryEntry apppools = new DirectoryEntry(metabasePath);
        DirectoryEntry newpool = apppools.Children.Add(appPoolName, "IIsApplicationPool");
        newpool.CommitChanges();
        Console.WriteLine("AppPool created.");
    }
    catch (Exception ex)
    {
        Console.WriteLine("Failed in CreateAppPool with the following exception: \n{0}", ex.Message);
    }
}

How can I change the user credentials under which this application pool is running?


回答1:


Add the following to your code just after the line where you create newpool:

DirectoryEntry newpool = 
            apppools.Children.Add(appPoolName, "IIsApplicationPool");
// Add this:
newpool.Properties["AppPoolIdentityType"].Value = 3;
newpool.Properties["WAMUserName"].Value = 
            Environment.MachineName + @"\" + username;
newpool.Properties["WAMUserPass"].Value = password;

You'll obviously need to add the string variables username and password to your CreateAppPool() method parameters as well.

Another thing you need to do, if you weren't already aware, is make sure your application pool user gets sufficient rights to access the IIS metabase, ASP.NET temp folders etc. You can do this by running the following command:

aspnet_regiis.exe -ga <username>

You can find this tool in the folder %SYSTEMROOT%\Microsoft.NET\Framework\v2.0.50727. I usually just shell out using System.Diagnostics.Process.

And finally, the application pool user will need (at least) read rights on the web folder for the app.




回答2:


aspnet_regiis.exe -ga <username>

Is probably not the best command to use.

You should add the APPPool user to the IIS_WPG group and grant rights using that group.



来源:https://stackoverflow.com/questions/662634/how-can-i-change-the-username-password-of-an-applicationpool-in-iis-from-c

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