name method documentacion comentarios c# .net asp.net-mvc iis application-pool

c# - method - Reiniciar(reciclar) un grupo de aplicaciones



param name c# (8)

A veces siento que lo simple es lo mejor. Y aunque sugiero que uno adapta la ruta real de una manera inteligente para trabajar de una manera más amplia en otros entornos, mi solución se parece a algo como:

ExecuteDosCommand(@"c:/Windows/System32/inetsrv/appcmd recycle apppool " + appPool);

Desde C #, ejecuta un comando de DOS que hace el truco. Muchas de las soluciones anteriores no funcionan en varias configuraciones y / o requieren que las características de Windows estén activadas (dependiendo de la configuración).

¿Cómo puedo reiniciar (reciclar) el conjunto de aplicaciones de IIS desde C # (.net 2)?

Apreciar si publica código de muestra?


Aquí vamos:

HttpRuntime.UnloadAppDomain();


El siguiente código funciona en IIS6. No probado en IIS7.

using System.DirectoryServices; ... void Recycle(string appPool) { string appPoolPath = "IIS://localhost/W3SVC/AppPools/" + appPool; using (DirectoryEntry appPoolEntry = new DirectoryEntry(appPoolPath)) { appPoolEntry.Invoke("Recycle", null); appPoolEntry.Close(); } }

También puede cambiar "Reciclar" para "Comenzar" o "Detener".


John,

Si está en IIS7 , esto lo hará si se detiene. Supongo que puede ajustar para reiniciar sin tener que mostrarse.

// Gets the application pool collection from the server. [ModuleServiceMethod(PassThrough = true)] public ArrayList GetApplicationPoolCollection() { // Use an ArrayList to transfer objects to the client. ArrayList arrayOfApplicationBags = new ArrayList(); ServerManager serverManager = new ServerManager(); ApplicationPoolCollection applicationPoolCollection = serverManager.ApplicationPools; foreach (ApplicationPool applicationPool in applicationPoolCollection) { PropertyBag applicationPoolBag = new PropertyBag(); applicationPoolBag[ServerManagerDemoGlobals.ApplicationPoolArray] = applicationPool; arrayOfApplicationBags.Add(applicationPoolBag); // If the applicationPool is stopped, restart it. if (applicationPool.State == ObjectState.Stopped) { applicationPool.Start(); } } // CommitChanges to persist the changes to the ApplicationHost.config. serverManager.CommitChanges(); return arrayOfApplicationBags; }

Si está en IIS6, no estoy tan seguro, pero podría intentar obtener el archivo web.config y editar la fecha de modificación o algo así. Una vez que se realiza una edición en web.config, la aplicación se reiniciará.


Reciclar código trabajando en IIS6:

/// <summary> /// Get a list of available Application Pools /// </summary> /// <returns></returns> public static List<string> HentAppPools() { List<string> list = new List<string>(); DirectoryEntry W3SVC = new DirectoryEntry("IIS://LocalHost/w3svc", "", ""); foreach (DirectoryEntry Site in W3SVC.Children) { if (Site.Name == "AppPools") { foreach (DirectoryEntry child in Site.Children) { list.Add(child.Name); } } } return list; } /// <summary> /// Recycle an application pool /// </summary> /// <param name="IIsApplicationPool"></param> public static void RecycleAppPool(string IIsApplicationPool) { ManagementScope scope = new ManagementScope(@"//localhost/root/MicrosoftIISv2"); scope.Connect(); ManagementObject appPool = new ManagementObject(scope, new ManagementPath("IIsApplicationPool.Name=''W3SVC/AppPools/" + IIsApplicationPool + "''"), null); appPool.InvokeMethod("Recycle", null, null); }



Tomé una ruta ligeramente diferente con mi código para reciclar el grupo de aplicaciones. Algunas cosas para tener en cuenta que son diferentes de lo que otros han proporcionado:

1) Usé una declaración de uso para asegurar la correcta eliminación del objeto ServerManager.

2) Estoy esperando que el grupo de aplicaciones termine de comenzar antes de detenerlo, para que no tenga problemas al tratar de detener la aplicación. Del mismo modo, estoy esperando que el grupo de aplicaciones termine de detenerse antes de intentar iniciarlo.

3) Estoy forzando que el método acepte un nombre de servidor real en lugar de volver a caer en el servidor local, porque pensé que probablemente debería saber con qué servidor está ejecutando esto.

4) Decidí iniciar / detener la aplicación en lugar de reciclarla, para poder asegurarme de que no iniciamos accidentalmente un grupo de aplicaciones que se detuvo por otro motivo, y para evitar problemas al tratar de reciclar una ya detenida grupo de aplicaciones.

public static void RecycleApplicationPool(string serverName, string appPoolName) { if (!string.IsNullOrEmpty(serverName) && !string.IsNullOrEmpty(appPoolName)) { try { using (ServerManager manager = ServerManager.OpenRemote(serverName)) { ApplicationPool appPool = manager.ApplicationPools.FirstOrDefault(ap => ap.Name == appPoolName); //Don''t bother trying to recycle if we don''t have an app pool if (appPool != null) { //Get the current state of the app pool bool appPoolRunning = appPool.State == ObjectState.Started || appPool.State == ObjectState.Starting; bool appPoolStopped = appPool.State == ObjectState.Stopped || appPool.State == ObjectState.Stopping; //The app pool is running, so stop it first. if (appPoolRunning) { //Wait for the app to finish before trying to stop while (appPool.State == ObjectState.Starting) { System.Threading.Thread.Sleep(1000); } //Stop the app if it isn''t already stopped if (appPool.State != ObjectState.Stopped) { appPool.Stop(); } appPoolStopped = true; } //Only try restart the app pool if it was running in the first place, because there may be a reason it was not started. if (appPoolStopped && appPoolRunning) { //Wait for the app to finish before trying to start while (appPool.State == ObjectState.Stopping) { System.Threading.Thread.Sleep(1000); } //Start the app appPool.Start(); } } else { throw new Exception(string.Format("An Application Pool does not exist with the name {0}.{1}", serverName, appPoolName)); } } } catch (Exception ex) { throw new Exception(string.Format("Unable to restart the application pools for {0}.{1}", serverName, appPoolName), ex.InnerException); } } }


este código funciona para mí solo llámalo para volver a cargar la aplicación.

System.Web.HttpRuntime.UnloadAppDomain()