【问题标题】:how to restart web service on remote server pragmatically in c#如何在 C# 中务实地重新启动远程服务器上的 Web 服务
【发布时间】:2017-11-22 05:43:32
【问题描述】:
我无法找到用于在远程服务器上使用类似于窗口服务的代码启动 Web 服务的类。
var sc = new System.ServiceProcess.ServiceController("mywebsite", "remoteservername");
sc.Start();
sc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running);
sc.Stop();
sc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped);
【问题讨论】:
标签:
c#
asp.net
asp.net-mvc
c#-4.0
c#-3.0
【解决方案1】:
Web 服务未列在 Windows 服务下。它在 IIS 下运行,要停止/启动它,您需要停止/启动运行此服务的应用程序池。如果您打算远程执行此操作,则需要在目标服务器上启用 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);
}
}
注意:
- 操作可以包含“开始”、“停止”或“回收”
- 运行此代码的帐户需要是目标服务器上的管理员。
如何在服务器上启用 WMI
【解决方案2】:
static void Main(string[] 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)
{
}
}