2008-10-16 133 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 
相關問題