我的代码如何在IIS中运行?

sha*_*oth 14 c# iis asp.net-mvc asp.net-mvc-3

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

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

是否有一些编程方式来检测我的代码是否在IIS下运行而不依赖于IIS版本?

RB.*_*RB. 27

看看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 :-(");
    }
}
Run Code Online (Sandbox Code Playgroud)