以编程方式从Windows 2003服务器控制IIS 7服务器

问题描述:

我们使用Windows 2003服务器运行各种作业。其中一些作业将应用程序池命令发送到运行IIS 6的Web服务器(回收,启动,停止)。现在我们有一台运行IIS 7的Windows 2008 Web服务器,并且我们想发送相同的命令。这全部使用C#完成。以编程方式从Windows 2003服务器控制IIS 7服务器

这是我们用来发送命令为IIS 6的代码:

var methodToInvoke = "Stop"; // could be "Stop", "Start", or "Recycle" 
var co = new ConnectionOptions 
{ 
    Impersonation = ImpersonationLevel.Impersonate, 
    Authentication = AuthenticationLevel.PacketPrivacy 
}; 

var objPath = string.Format("IISApplicationPool.Name='W3SVC/AppPools/{0}'", appPoolName); 
var scope = new ManagementScope(string.Format(@"\\{0}\root\MicrosoftIISV2", machineName), co); 

using (var mc = new ManagementObject(objPath)) 
{ 
    mc.Scope = scope; 
    mc.InvokeMethod(methodToInvoke, null, null); 
} 

此代码不能用于IIS 7,由于潜在的变化工作,所以我们目前正在尝试这样的:

using (ServerManager serverManager = ServerManager.OpenRemote(machineName)) 
{ 
    var appPool = serverManager.ApplicationPools[appPoolName]; 
    if (appPool != null) 
    { 
     appPool.Stop(); // or app.Start() or app.Recycle() 
     serverManager.CommitChanges(); 
    } 
} 

上述代码在我的工作站上运行良好,该工作站运行Windows 7(以及IIS 7.5)。但是,当我将这段代码部署到我们的应用程序服务器时,它不起作用。它得到这个错误:

System.InvalidCastException: 
Unable to cast COM object of type 'System.__ComObject' to interface type 
'Microsoft.Web.Administration.Interop.IAppHostWritableAdminManager'. 
This operation failed because the QueryInterface call on the COM component for the 
interface with IID '{FA7660F6-7B3F-4237-A8BF-ED0AD0DCBBD9}' failed due to the following error: 
Interface not registered (Exception from HRESULT: 0x80040155). 

从我的研究,这是由于IIS 7在Windows Server 2003服务器上不可用。 (我没有包括Microsoft.Web.Administration.dll文件。)

所以我的问题是:

  1. 是否有可能为IIS 7上面的代码在所有从Windows 2003服务器工作?
  2. 如果不是#1,有没有更好的方法来做到这一点?

从周围看它似乎不可能做你正在寻找的东西。包括dll文件是不够的。 据http://forums.iis.net/t/1149274.aspx ..

In order to use Microsoft.Web.Administration you need to have IIS installed, at the bare minimum you need to install the Configuration API's which are brought through installing the Management Tools.

Unfortunately there is no SDK that enables this and it has several dependencies on other components that wouldn't let you just take it to another machine and make it work (such as COM objects, DLL's, etc).

我会想知道,如果你已经找到一个办法解决这。

谢谢

+0

我最终在Web服务器本身上创建了一个Web服务,它将启动/停止/回收该服务器上的应用程序池。这个Web服务显然需要位于一个单独的应用程序池上,而不是它将更新的应用程序池。这不是一个非常安全的解决方案,但我正在使用内部Web服务器。 – 2010-12-07 14:23:50

+0

出现同样的问题,您的文章确认了我害怕的 - 管理API在Windows XP上无法正常工作。感谢帖子 – Jeremy 2011-09-14 17:57:30

尝试用DirectoryEntry控制IIS池。

请参见本主题: Check the status of an application pool (IIS 6) with C#

+0

他的问题的整个重点是如何管理IIS7。 – Jeremy 2011-09-14 17:56:35

Microsoft.Web.Administration,它依赖于System.Web.dll这是由框架4,而不是客户端配置文件提供。

+1

这不回答这个问题。 – 2012-09-25 02:28:19