我想編寫一個幫助函數來構建寫入日誌的異常消息。 代碼看起來象:如何確定正在執行的程序集是否爲Web應用程序或winform/console?
如果(IsWebApp)
{
使用的HttpContext獲取請求路徑和RawUrl }
其他
{
//別的它是一個winform /控制檯
使用作爲裝配得到執行路徑。
}
我想編寫一個幫助函數來構建寫入日誌的異常消息。 代碼看起來象:如何確定正在執行的程序集是否爲Web應用程序或winform/console?
如果(IsWebApp)
{
使用的HttpContext獲取請求路徑和RawUrl }
其他
{
//別的它是一個winform /控制檯
使用作爲裝配得到執行路徑。
}
使用HttpRuntime類:
if (!String.IsNullOrEmpty(HttpRuntime.AppDomainAppVirtualPath))
//ASP.Net
else
//Non-ASP.Net
您可以檢查,看看是否HttpContext.Current!= NULL。
錯誤。這將在ASP.Net AppDomain中的非請求線程中爲空。 – SLaks 2010-04-16 15:09:42
如何
If (Not System.Web.HttpContext.Current Is Nothing) Then
End If
或
if(System.Web.HttpContext.Current != null){
}
只是檢查一些對象只存在於Web應用程序,像HttpRuntime.AppVirtualPath
那SLaks建議。
如果它是一個web應用程序,您仍然要檢查HttpContext.Current
是否爲空。如果異常發生在沒有運行的代碼中,因爲它沒有任何上下文。例如,Session_OnEnd事件在服務器會話被刪除時運行,所以它沒有上下文。
我使用DomainManager類型的當前AppDomain。 MSDN documentation of AppDomainManager
public static class AspContext
{
public static bool IsAspNet()
{
var appDomainManager = AppDomain.CurrentDomain.DomainManager;
return appDomainManager != null && appDomainManager.GetType().Name.Contains("AspNetAppDomainManager");
}
}
您還可以檢查this other answer on SO
+1指出到我們的休息,在asp.net並非一切都是一個請求線程 - 每天學習新的東西:) – Ray 2010-04-16 15:14:47