检查 IIS 应用程序池的状态 [英] check the status of IIS Application Pool

查看:55
本文介绍了检查 IIS 应用程序池的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 Windows 服务,它将每 5 分钟获取一次 IIS 应用程序池状态信息并存储在数据库或文本文件中......比如运行或停止.

I am developing a windows service which will gets the IIS Application Pool status information in every 5 min and stored in database or text file ... like running or stopped.

获取以下异常消息:

Microsoft.Web.Administration.dll 中出现类型为System.UnauthorizedAccessException"的异常,但未在用户代码中处理附加信息:访问被拒绝.(来自 HRESULT 的异常:0x80070005 (E_ACCESSDENIED))

An exception of type 'System.UnauthorizedAccessException' occurred in Microsoft.Web.Administration.dll but was not handled in user code Additional information: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

以下是我试过的代码:

 static void Main(string[] args)
    {
        const double interval60Minutes = 5 * 5 * 1000; // milliseconds to one hour
        Timer checkForTime = new Timer(interval60Minutes);
        checkForTime.Elapsed += new ElapsedEventHandler(checkForTime_Elapsed);
        checkForTime.Enabled = true;
        Console.WriteLine("Waiting..");           
        Console.ReadLine();          
    }

    public static void checkForTime_Elapsed(object sender, ElapsedEventArgs e)
    {            
        GetApplicationPoolNames();
    }       

    public static string GetApplicationPoolNames()
    {
        ServerManager manager = new ServerManager();
        string status;
        //string DefaultSiteName = System.Web.Hosting.HostingEnvironment.ApplicationHost.GetSiteName();
        //Site defaultSite = manager.Sites[DefaultSiteName];
        string appVirtaulPath = HttpRuntime.AppDomainAppVirtualPath;
        string mname = System.Environment.MachineName;
        string appPoolName = string.Empty;
        manager = ServerManager.OpenRemote(mname);
        ObjectState result = ObjectState.Unknown;

        ApplicationPoolCollection applicationPoolCollection = manager.ApplicationPools;

        foreach (ApplicationPool applicationPool in applicationPoolCollection)
        {
            //result = manager.ApplicationPools[appPoolName].State;
            result = applicationPool.State;  *// here exception occures*
            Console.WriteLine("State : " + result);
            Console.ReadLine();
        }
   }

代码有什么问题?如果有任何其他方法可以实现这一点,请提供,因为这也有助于我了解异常消息的主要原因.

What is wrong in the code? If there are any other ways to achieve this please provide as that will also help me to understand the main cause of exception message.

感谢任何帮助.

谢谢.

推荐答案

提出的问题太老了,但想分享可能有助于解决此类错误/异常的解决方案,在尝试获取/读取 IIS 时发生服务器的应用程序池信息.

The asked question was too old but thought to share the solution which might help someone to resolve this kind of error/exception occurs when trying to get/read the IIS App Pool info of the server.

要在尝试访问 IIS 信息时解决未授权访问异常,首先使用 DirectoryEntry Class 如下所示 -

To resolve the Unauthorized Access Exception while trying to access the IIS info, First provide server credentials using DirectoryEntry Class like below -

DirectoryEntries appPools = new DirectoryEntry("IIS://" + ServerName + "/W3SVC/AppPools", UName, Pwd).Children;

这将提供相应服务器的 IIS 访问权限.

This will give the access of IIS of the respective server.

所以,修改后完整的GetApplicationPoolNames()方法是——

So, The complete GetApplicationPoolNames() method after modification is -

public static string GetApplicationPoolNames()
{
    // Get Server Credentials and Server Name from config file
    string UName = ConfigurationManager.AppSettings["User"];
    string Pwd = ConfigurationManager.AppSettings["Pass"];
    string ServerName = DT.Rows[i]["ServerName"].ToString().Trim(); //Server Names from db
    DirectoryEntries appPools = null;
    try
    {
        appPools = new DirectoryEntry("IIS://" + ServerName + "/W3SVC/AppPools", UName, Pwd).Children;
    }
    catch(Exception ex)
    {
        log.ErrorFormat("serviceLogic -> InsertStatus() -> IIS Pool App Region -> DirectoryEntries -> Error: ", ex.Message.ToString());
    }

    log.Info("IIS App Pool Section Started for " + System.Environment.MachineName.ToString());

    try
    {
        foreach (DirectoryEntry appPool in appPools)
        {
            log.Info("App Pool : " + appPool.Name.ToString());
            int intStatus = 0;
            string status = "";
            try
            {
                if (appPool.Name.ToString().ToLower().Trim() == DT.Rows[i]["AppPoolSrvName"].ToString().ToLower().Trim())
                {
                    log.Info("Process Started for App Pool : " + appPool.Name.ToString());

                    intStatus = (int)appPool.InvokeGet("AppPoolState");
                    switch (intStatus)
                    {
                        case 2:
                            status = "Running";
                            break;
                        case 4:
                            status = "Stopped";
                            break;
                        default:
                            status = "Unknown";
                            break;
                    }

                    //Store status info to db or file Logic goes here..

                    //Start App pool, If any application pool status is not Running.
                    if (status != "Running")
                        appPool.Invoke("Start", null);

                    log.Info("Process Completed for App Pool : " + appPool.Name.ToString());
                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat("serviceLogic -> InsertStatus() -> IIS Pool App Region -> Error: ", ex.Message);
            }
        }
    }
    catch (Exception ex)
    {
        log.ErrorFormat("serviceLogic -> InsertStatus() -> IIS Pool App Region -> DirectoryEntries -> Error: ", ex.Message);
    }
}

这篇关于检查 IIS 应用程序池的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆