-1

I want to Recycle application pool programmatically after some interval of time. I tried it using 2 methods that are specified below.

1)
    public static void RecycleAppPools()
    {
        ServerManager serverManager = new ServerManager();
        ApplicationPoolCollection appPools = serverManager.ApplicationPools;
        foreach (ApplicationPool ap in appPools)
        {
            //if(ap.Name== System.Security.Principal.WindowsIdentity.GetCurrent().Name)
            ap.Recycle();
        }
    }

The above is throwing exception of "Access denied"

  2) private static void RecycleApplicationPool(string appPoolId)
    {
        string appPoolPath = "IIS://localhost/W3SVC/AppPools/" + appPoolId;

        var appPool = new DirectoryEntry(appPoolPath);

      //  DirectoryEntry appPoolEntry = new DirectoryEntry(appPoolPath);

        appPool.Invoke("Recycle", null);
    }

This above method is throwing exception "System.Runtime.InteropServices.COMException: Unknown error (0x80005000)". Nothing is working for me.

I have given reference to Microsoft.Web.Administration and working on Visual studio 2015 express with framework 4.6.1 and IIS version is 10.0.14393.0

Please help if anyone can. Thanks in advance.

2 Answers2

2

You app, running in the pool, does not have the permission to recycle the app pool. The error is very clear and explicit. The permission is granted to members of the Administrator group.

The solution is to not recycle the app pool from the app pool. The whole idea of recycling the app pool on demand is bonkers. You should use app pool <recycle> settings to trigger this. If you insist use a scheduled task that runs as Admin.

Do not change the app to run as Admin.

Edit: The delegate solution @Zaitsman shows is also good

Remus Rusanu
  • 288,378
  • 40
  • 442
  • 569
  • You can also delegate these permissions apparently: https://blogs.msdn.microsoft.com/asiatech/2011/07/20/iis-7-delegate-remote-application-pool-recycling-for-non-administrator/ – zaitsman Dec 27 '17 at 08:40
  • @RemusRusanu I tried the code that adds an element to schedule recycling after some interval of time. I did that code on button click. It recycle pool for first click but when i refresh my page after that time interval it does not destroy any session that means pool did not get recycled. Please tell me where I am wrong. – Priyanka Bansal Dec 27 '17 at 10:06
2

As @RemusRusanu pointed out, in general this is not a good idea (think an attacker running code inside your app pool could do a whole new level of DDoS inside your box).

However, you may be able to do this if you delegate the user running your app pool with permissions as per this article: https://blogs.msdn.microsoft.com/asiatech/2011/07/20/iis-7-delegate-remote-application-pool-recycling-for-non-administrator/

zaitsman
  • 8,984
  • 6
  • 47
  • 79