Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a directive to detect ASP.NET?

I have a code library that works in ASP.NET, the SQL CLR, and stand-alone applications, and provides different features based on whether certain namespaces (such as System.Drawing) are available or not. Right now, I'm excluding those pieces of code manually, but it would be beneficial to have the C# compiler to it:

  • I could be lazier,
  • I could use one and the same library.

I know I can use #if directives to search for defines, and I could manually define something like ASP_NET, but if there's a way to do this automatically, that'd be even greater.

So, can I detect ASP.NET? Alternatively, can I detect whether certain referenced assemblies are available?

like image 348
Sören Kuklau Avatar asked Jan 18 '23 23:01

Sören Kuklau


1 Answers

There is no such predefined pre-processor directive for asp.net.

What most people do is look for the current HttpContext - the assumption being that if it is null, this is not a web context.

Another alternative is testing HttpRuntime.AppDomainAppId for null, to the similar assumption.

Other similar options:

System.Web.Hosting.HostingEnvironment.IsHosted == true
System.Web.HttpRuntime.Cache != null

And you can check that a web.config file exists.

like image 141
Oded Avatar answered Jan 31 '23 07:01

Oded