【问题标题】:How can my code find if it's running inside IIS?我的代码如何找到它是否在 IIS 中运行?
【发布时间】:2012-04-19 07:52:12
【问题描述】:

我的 C# 代码可能在 IIS(当前为 7.5,但我不想依赖特定版本)或其他地方的 MVC3 应用程序中运行。

看起来知道代码在 IIS 下运行的一种方法是 to check the current process name,但这种方法取决于硬编码文件名字符串。

是否有某种编程方式来检测我的代码是否在 IIS 下运行而不取决于 IIS 版本?

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-3 iis


    【解决方案1】:

    看看HostingEnvironment 类,尤其是IsHosted 方法。

    这将告诉您是否托管在 ApplicationManager 中,这将告诉您是否托管在 ASP.NET 中。

    严格来说,它不会告诉您您在 IIS 下运行,但我认为这实际上更符合您的需求。

    示例代码:

    // Returns the file-system path for a given path.
    public static string GetMappedPath(string path)
    {
        if (HostingEnvironment.IsHosted)
        {
            if (!Path.IsPathRooted(path))
            {
                // We are about to call MapPath, so need to ensure that 
                // we do not pass an absolute path.
                // 
                // We use HostingEnvironment.MapPath, rather than 
                // Server.MapPath, to allow this method to be used
                // in application startup. Server.MapPath calls 
                // HostingEnvironment.MapPath internally.
                return HostingEnvironment.MapPath(path);
            }
            else {
                return path;
            }
        }
        else 
        {
            throw new ApplicationException (
                    "I'm not in an ASP.NET hosted environment :-(");
        }
    }
    

    【讨论】:

      【解决方案2】:

      看看ServiceController 类。服务名还是会被硬编码,但是服务名改名的几率比较低。

      您也可以使用netstat -ab 找出端口 80 上运行的内容。

      【讨论】:

      • 仅仅因为 IIS 在端口 80 上运行并不意味着他的应用程序托管在 IIS 中。反之亦然 - IIS 可以在任何其他端口(例如 8080)上运行
      • 是的。这就是推荐使用 ServiceController 类的原因。
      • ServiceController 所能做的只是告诉您 IIS 服务是否正在运行,而不是当前代码是否在该 IIS 中运行。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-21
      • 2016-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-21
      相关资源
      最近更新 更多