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

前端 未结 7 1478
被撕碎了的回忆
被撕碎了的回忆 2020-12-06 02:49

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 i

相关标签:
7条回答
  • 2020-12-06 03:09
    • BrowserInteropHelper..::.IsBrowserHosted Property

    Gets a value that specifies whether the current Windows Presentation Foundation (WPF) application is browser hosted.

    Thats how its done in XBAP

    • Performing Browser Detection Using ASP.NET

    or if you have an appdomain do reflection and get something from it? using

    • Reflection CallContext
    0 讨论(0)
  • 2020-12-06 03:09

    I think the very best thing to do is to split up the library into 2 dlls, one that's truly generic, and one (the one that requires ASP.NET) that only gets loaded in the website. Checking if it's currently running in ASP.NET feels like a bit of a hack.

    Ofcourse it depends on the situation wether or not you can easily do this.

    0 讨论(0)
  • 2020-12-06 03:13

    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.

    0 讨论(0)
  • 2020-12-06 03:17

    You can Find out the current process name:

    Process p = Process.GetCurrentProcess();
    string assemblyName = p.ProcessName;
    

    and then check if this is the ASP.NET process name

    0 讨论(0)
  • 2020-12-06 03:20

    The best option is a config setting.

    It's better for testability; it's better because it's an obvious statement of how the code will work, and it's better because it doesn't rely on implementation details; you specifically branch from a value you set. It may be that the decision you are making is non-obvious and your variable/config can be suggestive of the reasoning.

    It's the option I'd go for.

    0 讨论(0)
  • 2020-12-06 03:29

    You can check for

    HttpContext.Current
    

    If it is not null then it is run from a web app.

    See HttpContext.Current Property

    0 讨论(0)
提交回复
热议问题