How can a .NET code know whether it is running within a web server application?
.net, asp.net
Solution
Trying to solve another problem, I found a good solution for this one. There is a private method `System.Configuration.SettingsPropertyValue.IsHostedInAspnet`, which does exactly what I need. Being a private method, I do not want to call it (though I could using reflection), but its implementation is trivial:
private bool IsHostedInAspnet()
{
return (AppDomain.CurrentDomain.GetData(".appDomain") != null);
}
(according to Reflector)
Looks like there is a special key in the app domain data - ".appDomain", which is set when running in ASP.NET web server.
I will stick to that.
Problem
I have a library code, which should be aware whether it is executed in the context of a web server or standalone application server. The obvious that comes to mind is to check the name of the application configuration file and if it is web.config - then this is a web server, otherwise - standalone application server. Another way is to look for something like "Temporary ASP.NET files" in the path of the shadow folder. But I dislike both of these, since they seem too hacky and fragile. Is there a robust way to do what I want? Thanks. P.S. One may define a dedicated app config setting - IsWebServer, but I dislike it even more. EDIT: While looking for a solution to another problem, I think I solved this one - the details are here