Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
690 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...