Home > Development > Determine current execution context (ASP.NET or Winforms)

Determine current execution context (ASP.NET or Winforms)

October 5th, 2007 leandrodg Leave a comment Go to comments 1,511 views

I’ve searched over the internet for this and couldn’t find anything.

A method I’m working on should have a different behavior when called in a Web Application (Webforms) and a Windows Application (Winforms).

This is what I came up with, using Reflection:

	if (Assembly.GetEntryAssembly() != null)
	{
		// Running on Winforms context
	}
	else
	{
		// Running on ASP.NET context
	}

There are probably other ways to do it, I’ve tested this one and it works great.

Update (2007-16-10):

Turns out there is an easier way to do this, just got it from a co-worker. Instead of Assembly.GetEntryAssembly() you can use HttpContext.Current, but you’ll have to be careful with threading in ASP .NET forms, as seen in http://www.odetocode.com/Articles/112.aspx (HttpContext.Current could be null while running on ASP .NET).

  1. May 5th, 2008 at 02:08 | #1

    Hey! Thanks for the tip. I was using HttpContext.Current but found that it was null when invoking methods via reflection. Using Assembly.GetEntryAssembly() allows for this scenario. I combined the two checks to be safe:

    if (Assembly.GetEntryAssembly() != null && HttpContext.Current == null)

    Thanks again!

    Jimmy

  2. December 13th, 2008 at 16:31 | #2

    Thanks!,

  1. March 26th, 2009 at 03:26 | #1