2008-10-16 132 views
15

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

下面回答了我目前使用的解决方案。


我希望有人能添加评论,为什么这个问题已经得到downvoted和/或提出一个更好的方式来问吧!我只能假设至少有一些人已经看过这个问题,并说“ASP.NET代码是一个笨蛋,.NET代码”。

+0

您可能会发现下面的SO后你的答案。 http://stackoverflow.com/questions/2091866/how-can-a-net-code-know-whether-it-is-running-within-a-web-server-application/2092246#2092246 – deostroll 2011-10-03 13:37:03

回答

-1

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

首先,确保您的项目引用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; 
    } 
    } 
} 
+1

在实际请求之外不起作用。 – ygoe 2014-06-26 10:25:07

-2
If HttpContext Is Nothing OrElse HttpContext.Current Is Nothing Then 
    'Not hosted by web server' 
End If 
+1

HttpContext是类的名称,所以HttpContext不能为null。 – yfeldblum 2008-10-16 19:13:16

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 ... 
    } 
} 
+4

不错的想法和方式,因为我需要的是复杂的,当在ASP.NET下运行时调用少量方法时抛出异常。 – 2008-10-17 05:36:42

+0

如果定义是“在* IIS进程*中运行”,而不是“用当前/有效的* IIS请求*运行”,这将在线程中运行时“失败”(这在某些情况下很重要)。所以最后还是有很多代码来显示`HttpContext.Current!= null`,它具有上面提到的问题..我并不反对这样的设计,但它与原始问题相切,并且具体上下文需要被解释。 – user2864740 2018-02-08 19:19:24

12

HttpContext.Current也可以在ASP.NET空,如果你使用的是异步方法,如异步任务在不共享原始线程的HttpContext一个新的线程发生。这可能是也可能不是你想要的,但如果不是的话,我相信HttpRuntime.AppDomainAppId在ASP.NET过程的任何地方都是非空的,而在其他地方是空的。

+1

使用`HttpRuntiime.AppDomainAppId`与使用`HostingEnvironment.IsHosted`的[ghigad的答案](http://stackoverflow.com/a/28993766/9664)有什么优势? – 2017-02-24 15:14:09

2

试试这个:

using System.Web.Hosting; 

// ... 

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

为我工作!

HostingEnvironment.IsHosted详细信息...

0
using System.Diagnostics; 

if (Process.GetCurrentProcess().ProcessName == "w3wp") 
    //ASP.NET 
相关问题