如何确定.NET代码是否在ASP.NET进程中运行?
我有一个通用类的实例,将在 ASP.NET和独立程序下执行。此代码对于正在运行的进程是敏感的 - 也就是说,如果在ASP.NET下运行 ,则不应调用certin方法。如何确定代码是否在ASP.NET 进程中执行?如何确定.NET代码是否在ASP.NET进程中运行?
下面回答了我目前使用的解决方案。
我希望有人能添加评论,为什么这个问题已经得到downvoted和/或提出一个更好的方式来问吧!我只能假设至少有一些人已经看过这个问题,并说“ASP.NET代码是一个笨蛋,.NET代码”。
回答:
这是我对这个问题的回答。
首先,确保您的项目引用System.Web,并确保您的代码文件是“using System.Web”。
public class SomeClass {     public bool RunningUnderAspNet { get; private set; } 
    public SomeClass() 
    // 
    // constructor 
    // 
    { 
    try { 
     RunningUnderAspNet = null != HttpContext.Current; 
    } 
    catch { 
     RunningUnderAspNet = false; 
    } 
    } 
} 
回答:
If HttpContext Is Nothing OrElse HttpContext.Current Is Nothing Then     'Not hosted by web server' 
End If 
回答:
我觉得你真的想要做的是重新考虑你的设计。一个更好的方法是使用一个Factory类,它根据应用程序的启动方式生成不同版本的类(旨在实现接口,以便可以交换使用它们)。这将使代码本地化,以在一个地方检测基于web和非web的使用情况,而不是将其散布在您的代码中。
public interface IDoFunctions { 
    void DoSomething(); 
} 
public static class FunctionFactory 
{ 
    public static IDoFunctions GetFunctionInterface() 
    { 
    if (HttpContext.Current != null) 
    { 
     return new WebFunctionInterface(); 
    } 
    else 
    { 
     return new NonWebFunctionInterface(); 
    } 
    } 
} 
public IDoFunctions WebFunctionInterface 
{ 
    public void DoSomething() 
    { 
     ... do something the web way ... 
    } 
} 
public IDoFunctions NonWebFunctionInterface 
{ 
    public void DoSomething() 
    { 
     ... do something the non-web way ... 
    } 
} 
回答:
HttpContext.Current也可以在ASP.NET空,如果你使用的是异步方法,如异步任务在不共享原始线程的HttpContext一个新的线程发生。这可能是也可能不是你想要的,但如果不是的话,我相信HttpRuntime.AppDomainAppId在ASP.NET过程的任何地方都是非空的,而在其他地方是空的。
回答:
试试这个:
using System.Web.Hosting; // ... 
if (HostingEnvironment.IsHosted) 
{ 
    // You are in ASP.NET 
} 
else 
{ 
    // You are in a standalone application 
} 
为我工作!
见HostingEnvironment.IsHosted详细信息...
回答:
using System.Diagnostics; if (Process.GetCurrentProcess().ProcessName == "w3wp") 
    //ASP.NET 
以上是 如何确定.NET代码是否在ASP.NET进程中运行? 的全部内容, 来源链接: utcz.com/qa/261114.html

