我的代码如何确定它是否在IIS内运行?

15

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

看起来知道代码是否在IIS下运行的一种方法是检查当前进程名称,但这种方法取决于硬编码的文件名字符串。

有没有某种程序化方式可以检测我的代码正在IIS下运行而不依赖于IIS版本?

2个回答

29

看一下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 :-(");
    }
}

-3

看一下ServiceController类。服务名称仍将是硬编码的,但服务更改名称的可能性相对较低。

您还可以使用netstat -ab查找在端口80上运行的内容。


1
仅仅因为IIS运行在80端口并不意味着他的应用程序正在IIS中托管。反之亦然——IIS可以在任何其他端口上运行(例如8080)。 - RB.
没错。这就是为什么建议使用ServiceController类的原因。 - pikzen
3
ServiceController只能告诉你IIS服务是否正在运行,无法告诉你当前代码是否在该IIS中运行。 - Mark

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接