如何在 C# 中实用地重启远程服务器上的 Web 服务

how to restart web service on remote server pragmatically in c#

我找不到 class 用于在远程服务器上启动 Web 服务的代码,就像我们为 window 服务使用的代码一样。

        var sc = new System.ServiceProcess.ServiceController("mywebsite", "remoteservername");
        sc.Start();
        sc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running);
        sc.Stop();
        sc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped);

Web 服务未在 Windows 服务下列出。它在 IIS 下 运行ning,要 stop/start 您需要停止/启动应用程序池,此服务在 运行ning 下。如果您计划远程执行此操作,则需要在目标服务器上启用 WMI。为方便起见,请提供一个代码来为您执行此操作:

public void PoolAction(String servername, String AppPoolName, String action)
    {
        StringBuilder sb = new StringBuilder();
        ConnectionOptions options = new ConnectionOptions();
        options.Authentication = AuthenticationLevel.PacketPrivacy;
        options.EnablePrivileges = true;
        ManagementScope scope = new ManagementScope(@"\" +
            servername + "\root\MicrosoftIISv2", options);

        // IIS WMI object IISApplicationPool to perform actions on IIS Application Pool
        ObjectQuery oQueryIISApplicationPool =
            new ObjectQuery("SELECT * FROM IISApplicationPool");

        ManagementObjectSearcher moSearcherIISApplicationPool =
            new ManagementObjectSearcher(scope, oQueryIISApplicationPool);
        ManagementObjectCollection collectionIISApplicationPool =
            moSearcherIISApplicationPool.Get();
        foreach (ManagementObject resIISApplicationPool in collectionIISApplicationPool)
        {
            if (resIISApplicationPool["Name"].ToString().Split('/')[2] == AppPoolName)
            {
                // InvokeMethod - start, stop, recycle can be passed as parameters as needed.
                resIISApplicationPool.InvokeMethod(action, null);
            }
        }

注:

  • 操作可以包含 'Start'、'Stop' 或 'Recycle'
  • 此代码所使用的帐户运行 需要是目标服务器上的管理员。

如何在服务器上启用 WMI

static void Main(字符串[] args) {

        try
        {
        using (ServerManager manager = new ServerManager())
        {
            var iisManager = ServerManager.OpenRemote("YourServerName");

            Microsoft.Web.Administration.Site site = iisManager.Sites.Where(q => q.Name.Equals("YourSiteName")).FirstOrDefault();

            if (site.State== site.Start())
            {
                site.Stop();
            }
            else
            {
                site.Start();
            }

            manager.CommitChanges();


            }

        }
        catch (Exception ex)
            {

            }
    }