Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
674 views
in Technique[技术] by (71.8m points)

asp.net - How can a .NET code know whether it is running within a web server application?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...