I have an application in .Net that does various admin/config for other applications. I need to be able to stop and start the app pool. I’ve achieved this, but only if I run the app pool as local system (which is generally accepted as a bad idea).
Initially I started appcmd.exe with Process.Start (using appropriate ProcessStartInfo object), but this eventually lead me to an Exit Code of -1073741502, further research suggests that I need to debug using the windows SDK as it has something to do with an assembly not loading, so I found what seems like a simpler solution in the Microsoft.Web.Administration namespace:
I use the below code, but it seems to require the AppPool running it has an identity of local system (otherwise I get System.UnauthorizedAccessException) – is there a way to start/stop with a less privileged account (I would prefer using Application Identity) – although temporarily elevating permissions is also acceptable.
Dim serverManager As New ServerManager()
Dim applicationPoolCollection As ApplicationPoolCollection = serverManager.ApplicationPools
For Each applicationPool As ApplicationPool In applicationPoolCollection
If applicationPool.Name = appPoolName Then
applicationPool.Stop()
applicationPool.Start()
End If
Next
I’ve set a custom account as the Identity, but I can’t work out what the minimum ACL for that user needs to be. As a test, I added the user to the local administrators group, but still get System.UnauthorizedAccessException – this suggests I need to configure a particular permission for the user, but I’m unsure what this is or how to do it. Can anyone help?
Using @CarlosAg answer, the following solution works:
Create a new User and put them in the Administrators Group
Create a web service to run the restart code, put it in it’s own application pool running as a user you created (configure appropriate app pool properties, e.g. queue length etc)
a. Put below code in your web method (or begin_reqest) to prevent it from being called externally (I think there are other ways to do this in IIS as well, but this was the quickest method I found)
b. Add additional authentication to web service code as you see fit (we have a Single sign on service I can use).
Reference this service from the web site which is running in an app pool under ApplicationIdentity
This works.
Code: