当前位置首页 > IIS知识

.NET获取IIS7.0及以上版本托管服务信息

阅读次数:382 次  来源:admin  发布时间:

近期写了个扫描IIS托管站点然后定期注册到Consul的小工具,随意网上拷贝了个帮助类,搞完本机测试没问题,扔到服务器发现硕大的一个异常。。

System.Runtime.InteropServices.COMException (0x80005000): 未知错误(0x80005000)

在 System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)

在 System.DirectoryServices.DirectoryEntry.Bind()

在 System.DirectoryServices.DirectoryEntry.get_IsContainer()

在 System.DirectoryServices.DirectoryEntries.ChildEnumerator..ctor(DirectoryEntry container)

查了查资料发现是:

这段异常代码表明 IIS://localhost/W3SVC/1 的ADSI provider不存在或者无法访问。

打开IIS管理器你可以看到服务器的localhost(即默认站点)是存在的并正在运行,且主站点ID确实是1。这说明问题是出现在 IIS://localhost的ADSI provider。

坦白点就是:而IIS 7默认并没有安装ADSI provider。

解决方案:“控制面板”->“程序和功能”->面板左侧“打开或关闭windows功能”->“Web服务器(IIS)”->“管理工具”->“IIS 6管理兼容性”->“IIS 元数据库兼容性”。

代码部分比较简单:

using System.ServiceProcess;
using System.DirectoryServices;
public class IISManager
{
    public static List<IISWebServiceInfo> GetLocalWebSeriviceInfo_IIS6()
    {
        DirectoryEntry rootfolder = new DirectoryEntry("IIS://localhost/W3SVC");
        foreach (DirectoryEntry child in rootfolder.Children)
        {
            if (child.SchemaClassName == "IIsWebServer")
            { 
                child.Properties["ServerComment"].Value.ToString();//服务名     
                child.Properties["ServerState"].Value;//服务状态 
                child.Properties["ServerBindings"].Value;//绑定信息
            }
        } 
    } 
}

弊端比较明显就是只支持IIS6及以下版本(安装ADSI provider),太麻烦。。

IIS7.0及以上版本获取服务信息可以使用Microsoft.Web.Administration,Nuget就能搜到

.NET获取IIS7.0及以上版本托管服务信息

不得不说微软还是比较拼的。。这是要跨平台的节奏啊(Linux版IIS指日可待了吗。。。)

代码更简单了:

 using Microsoft.Web.Administration;
    class Program
    {
        static void Main(string[] args)
        {
             ServerManager sm = new ServerManager();
            foreach (var s in sm.Sites)
            {
                Console.WriteLine("网站名称:{0}", s.Name);
                Console.WriteLine("运行状态:{0}", s.State.ToString());
                foreach (var tmp in s.Bindings)
                {
                    System.Console.WriteLine("\t类型:{0}", tmp.Protocol);
                    System.Console.WriteLine("\tIP 地址:{0}", tmp.EndPoint.Address.ToString());
                    System.Console.WriteLine("\t端口:{0}", tmp.EndPoint.Port.ToString());
                    System.Console.WriteLine("\t主机名:{0}", tmp.Host);
                }
            }
            Console.ReadKey();
        }
    }

当然,在windows操作系统获取IIS信息是需要管理员权限的

上一篇:《ASP.NETSignalR系列》第四课SignalR自托管(不用IIS)
下一篇:Centos7下安装Apache2+MySQL+PHP7