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

时间:2008-10-16 18:56:40

标签: c# .net asp.net

我有一个通用类的实例,它将在下面执行 ASP.NET和独立程序。这段代码对它的过程很敏感 正在运行 - 也就是说,有一些不应该调用的certin方法 在ASP.NET下运行。如何确定代码是否在ASP.NET中执行 过程

我目前使用的解决方案如下所示。


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

6 个答案:

答案 0 :(得分:12)

如果您使用异步方法,则

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

答案 1 :(得分:2)

试试这个:

using System.Web.Hosting;

// ...

if (HostingEnvironment.IsHosted)
{
    // You are in ASP.NET
}
else
{
    // You are in a standalone application
}

为我工作!

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

答案 2 :(得分:1)

我认为你真正想做的是重新思考你的设计。更好的方法是使用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 ...
    }
}

答案 3 :(得分:0)

Exception

答案 4 :(得分:-1)

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

首先,确保您的项目引用System.Web并且您的代码文件是“使用System.Web;”。

public class SomeClass {

  public bool  RunningUnderAspNet    { get; private set; }


  public SomeClass()
    //
    // constructor
    //
  {
    try {
      RunningUnderAspNet = null != HttpContext.Current;
    }
    catch {
      RunningUnderAspNet = false;
    }
  }
}

答案 5 :(得分:-2)

If HttpContext Is Nothing OrElse HttpContext.Current Is Nothing Then
  'Not hosted by web server'
End If