I have an instance of a general purpose class that will be executed both under ASP.NET and a stand alone program. This code is sensative to the process where it is being run
I think what you really want to do is rethink your design. A better way to do this is to use a Factory class that produces different versions of the classes you need (designed to implement interfaces so you can use them interchangeably) depending on how the application is started. This will localize the code to detect web- and non-web-based usage in one place rather than scattering it all over your code.
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 ...
}
}
HttpContext.Current can also be null within ASP.NET if you're using asynchronous methods, as the asynchronous task happens in a new thread that doesn't share the HttpContext of the original thread. This may or may not be what you want, but if not then I believe that HttpRuntime.AppDomainAppId will be non-null anywhere in an ASP.NET process and null elsewhere.
using System.Diagnostics;
if (Process.GetCurrentProcess().ProcessName == "w3wp")
//ASP.NET
This is my answer to the question.
First, make sure your project references System.Web and that your code file is "using System.Web;".
public class SomeClass {
public bool RunningUnderAspNet { get; private set; }
public SomeClass()
//
// constructor
//
{
try {
RunningUnderAspNet = null != HttpContext.Current;
}
catch {
RunningUnderAspNet = false;
}
}
}
If HttpContext Is Nothing OrElse HttpContext.Current Is Nothing Then
'Not hosted by web server'
End If
Try this:
using System.Web.Hosting;
// ...
if (HostingEnvironment.IsHosted)
{
// You are in ASP.NET
}
else
{
// You are in a standalone application
}
Worked for me!
See HostingEnvironment.IsHosted for details...