我的C#代码可能正在IIS(当前版本为7.5,但我不想依赖于特定版本)或其他地方的MVC3应用程序中运行。
看起来知道代码是否在IIS下运行的一种方法是检查当前进程名称,但这种方法取决于硬编码的文件名字符串。
有没有某种程序化方式可以检测我的代码正在IIS下运行而不依赖于IIS版本?
我的C#代码可能正在IIS(当前版本为7.5,但我不想依赖于特定版本)或其他地方的MVC3应用程序中运行。
看起来知道代码是否在IIS下运行的一种方法是检查当前进程名称,但这种方法取决于硬编码的文件名字符串。
有没有某种程序化方式可以检测我的代码正在IIS下运行而不依赖于IIS版本?
看一下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 :-(");
}
}
看一下ServiceController类。服务名称仍将是硬编码的,但服务更改名称的可能性相对较低。
您还可以使用netstat -ab
查找在端口80上运行的内容。