如何才能.NET code知道它是否是Web服务器应用程序中运行? [英] How can a .NET code know whether it is running within a web server application?
问题描述
我有一个库code,无论是在Web服务器或单机应用程序服务器的上下文中执行,这应该知道。
想到的最明显的是检查应用程序配置文件的名称,如果它是web.config中 - 那么这是一个Web服务器,否则 - 独立应用程序服务器
另一种方式是在阴影文件夹的路径寻找类似临时ASP.NET文件。
不过,我不喜欢这两个,因为他们也似乎哈克和脆弱。有没有一种可靠的方法做我想要什么?
感谢。
P.S。
有人可能会定义一个专用的应用程序配置设置 - IsWebServer,但我不喜欢它更
编辑:
在寻找一个解决一个问题,我想我解决这一个 - 细节<一个href="http://stackoverflow.com/questions/2091866/how-can-a-net-$c$c-know-whether-it-is-running-within-a-web-server-application/2092246#2092246">here
试图解决另一个问题,我发现这一个很好的解决方案。
有一个私人的方法 System.Configuration.SettingsPropertyValue.IsHostedInAspnet
,这不正是我需要的。作为一个私有方法,我不想把它(虽然我可以使用反射),但它的实现很简单:
私人布尔IsHostedInAspnet()
{
返程(AppDomain.CurrentDomain.GetData(的AppDomain。)!= NULL);
}
(根据反射镜)
看起来像有一个特殊的关键在应用程序域的数据 - .appDomain,在ASP.NET Web服务器中运行时,它被设置
我会坚持到底。 P>
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
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.
这篇关于如何才能.NET code知道它是否是Web服务器应用程序中运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!