如何确定.NET代码是否在ASP.NET进程中运行?

我有一个通用类的实例,它将在ASP.NET和独立程序下执行。 此代码对正在运行的进程很敏感 – 也就是说,如果在ASP.NET下运行,则不应调用certin方法。 如何确定代码是否在ASP.NET进程中执行?

我目前使用的解决方案将在下面解答。


我希望有人会就为什么这个问题得到落实和/或提出更好的方式来提出评论! 我只能假设至少有些人看过这个问题并说“什么是白痴,ASP.NET代码是.NET代码”。

如果您使用异步方法,则HttpContext.Current在ASP.NET中也可以为null,因为异步任务发生在不共享原始线程的HttpContext的新线程中。 这可能是您想要的,也可能不是,但如果没有,那么我相信HttpRuntime.AppDomainAppId在ASP.NET进程中的任何地方都是非null,而在其他地方则为null。

试试这个:

 using System.Web.Hosting; // ... if (HostingEnvironment.IsHosted) { // You are in ASP.NET } else { // You are in a standalone application } 

为我工作!

有关详细信息,请参阅HostingEnvironment.IsHosted

我想你真正想做的是重新思考你的设计。 更好的方法是使用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 ... } } 
 using System.Diagnostics; if (Process.GetCurrentProcess().ProcessName == "w3wp") //ASP.NET 

这是我对这个问题的回答。

首先,确保您的项目引用System.Web并且您的代码文件是“使用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