I would like to write a helper function which build the exception message to write to a log.
The code look like:
if(IsWebApp)
{
use HttpContext to get the Request Path and RawUrl
}
else
{
//else it a winform/console
Use Assembly to get executing path.
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Use the HttpRuntime class:
if (!String.IsNullOrEmpty(HttpRuntime.AppDomainAppVirtualPath))
//ASP.Net
else
//Non-ASP.Net
Method 2
Just check for some object that only exists in a web application, like HttpRuntime.AppVirtualPath that SLaks suggested.
If it’s a web application, you would still want to check if HttpContext.Current is null. If the exception occurs in code that is not run beacuse of a request, it doesn’t have any context. The Session_OnEnd event for example runs when a server session is removed, so it doesn’t have the context.
Method 3
You can check to see if HttpContext.Current != null.
Method 4
How about
If (Not System.Web.HttpContext.Current Is Nothing) Then End If
or
if(System.Web.HttpContext.Current != null){
}
Method 5
I use the DomainManager type of Current 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");
}
}
You can also check this other answer on SO
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0