Wednesday, January 13, 2010

Identifying whether execution context is win or web

When writing components which targets both web and desktop applications, there might be instances where there is need to check under which context the code is running.

Checking System.Web.HttpContext.Current won't work always. If the code is running under the context of main thread this always works. But if a thread is spawn, in the new thread System.Web.HttpContext.Current will return null even if it is running under web context.

Some debugging showed me that System.Web.HttpRuntime.AppDomainId is the right candidate for checking this. System.Web.HttpRuntime.AppDomainId returns null when the code is running under windows context, but always returns a non-null string value while running under web context regardless of whether the code is running under main thread or a spawned thread.

So the below piece of code can be used to check whether the code is running under web context.
/// <summary>
/// Specifies whether the current execution context is Web.
/// </summary>
/// <returns>True if current context is Web.</returns>
public bool IsWebApplicationContext()
    return !string.IsNullOrEmpty(System.Web.HttpRuntime.AppDomainId);

No comments:

Post a Comment