我的C#代码可能运行在IIS下的MVC3应用程序(目前为7.5,但我不想依赖于特定版本)或其他地方。我的代码如何在IIS中运行?
看起来像知道在IIS下运行代码的一种方法是to check the current process name,但此方法取决于具有硬编码的文件名字符串。
是否有一些编程方式来检测我的代码是否在IIS下运行,而不取决于IIS版本?
我的C#代码可能运行在IIS下的MVC3应用程序(目前为7.5,但我不想依赖于特定版本)或其他地方。我的代码如何在IIS中运行?
看起来像知道在IIS下运行代码的一种方法是to check the current process name,但此方法取决于具有硬编码的文件名字符串。
是否有一些编程方式来检测我的代码是否在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
只是因为IIS在端口80上运行,并不意味着他的应用程序被托管在IIS。反过来也是如此 - IIS可以在任何其他端口上运行(例如8080) – 2012-04-19 08:11:44
是真的。这就是推荐使用ServiceController类的原因。 – pikzen 2012-04-19 08:13:22
所有ServiceController都可以告诉您IIS服务是否正在运行,而不是当前代码是否在该IIS中运行。 – Mark 2013-08-27 21:10:12