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 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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With