检测IIS网站被暂停

hwc*_*rwe 0 c# iis suspend detection web

我目前能够使用以下代码检测 IIS 网站是否已启动/暂停/停止:

public int GetWebsiteStatus(string machineName, int websiteId)
{
    DirectoryEntry root = new DirectoryEntry(
        String.Format("IIS://{0}/W3SVC/{1}", machineName, websiteId));
    PropertyValueCollection pvc = root.Properties["ServerState"];
    return pvc.Value
    // - 2: Website Started
    // - 4: Website Stopped
    // - 6: Website Paused
}
Run Code Online (Sandbox Code Playgroud)

我还想检测一个网站是否被暂停。如果网站被暂停,上面的方法仍然返回 2(这是正确的),但对我来说还不够。

我找不到任何可以为 IIS6 及更高版本完成工作的代码。

cir*_*rus 5

啊,你的意思是应用池因为超时配置而停止了吗?这是一个与网站不同的状态还记得吗?嗯,当然,您可以更改设置,使其不回收,但您也可以尝试使用这样的代码;

首先,添加对\Windows\System32\inetsrv\Microsoft.Web.Administration.dll 的引用,然后;

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Web.Administration;
namespace MSWebAdmin_Application
{
    class Program
    {
        static void Main(string[] args)
        {
            ServerManager serverManager = new ServerManager();
            Site site = serverManager.Sites["Default Web Site"];

            // get the app for this site
            var appName = site.Applications[0].ApplicationPoolName;
            ApplicationPool appPool = serverManager.ApplicationPools[appName];

            Console.WriteLine("Site state is : {0}", site.State);
            Console.WriteLine("App '{0}' state is : {1}", appName, appPool.State);

            if (appPool.State == ObjectState.Stopped)
            {
                // do something because the web site is "suspended"
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

该代码将独立检查您的 appPool 的状态,而不是您的网站。网站可能会返回“已启动”,而 appPool 会返回“已停止”。

看看它是否适用于您的情况。