Manage IIS website from ASP.NET code
Controlling the current ASP.NET application running on IIS from the code
Microsoft made IIS management from the ASP.NET code itself much easer and accessible right out of the box by introducing Microsoft.Web.Administration library.
Simply by adding the reference in your project to Microsoft.Web.Administration library you are getting options to manage websites hosted on the IIS where application is running. One of the requirements beside referencing Microsoft.Web.Administration library is setting your Application Pool to run under LocalSystem account.
Running website with application pool under different account that LocalSystem will throw System.UnauthorizedAccessException when trying to use Microsoft.Web.Administration.ServerManager
This can be easily done through the command prompt by simply executing appcmd.exe with parameters
%windir%\system32\inetsrv\appcmd.exe set AppPool <your AppPool> -processModel.identityType:LocalSystem
If you are more GUI person, application pool identity can be set from Advanced Properties of the application pool in Internet Information Services (IIS) Manager tool.
More on how to manage Application Pool identity on IIS can be found on MSDN online documentation https://docs.microsoft.com/en-us/iis/manage/configuring-security/application-pool-identities
Useful methods for managing the website especially if you want to manage currently running website from its own code can be fount in System.Web.HostingEnvironment which is part of System.Web assembly reference.
The following extension methods help using Microsoft.Web.Administration in combination with System.Web.HostingEnvironment to controll teh currently running website.
public static Site GetCurrentWebsite(this ServerManager serverManager) { return serverManager.Sites.Where(s => s.Name.Equals(HostingEnvironment.ApplicationHost.GetSiteName())).FirstOrDefault(); } public static ApplicationPool GetCurrentApplicationPool(this ServerManager serverManager) { return serverManager.ApplicationPools[serverManager.GetCurrentWebsite().Applications["/"].ApplicationPoolName]; }
Keep in mind that class Microsoft.Web.Administration.ServerManager so make sure you dispose it after initializing or wrap it with using:
public static void RecycleApplicationPool() { using (ServerManager serverManager = new ServerManager()) { serverManager.GetCurrentApplicationPool().Recycle(); } }
References
- https://msdn.microsoft.com/en-us/library/microsoft.web.administration.servermanager(v=vs.90).aspx
- https://msdn.microsoft.com/en-us/library/system.web.hosting.hostingenvironment(v=vs.110).aspx
- More on how to manage Application Pool identity on IIS
Disclaimer
Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.
Comments for this article