How do I determine if the executing assembly is a web app or winform/console?

后端 未结 5 1652
灰色年华
灰色年华 2021-01-18 02:14

I would like to write a helper function which build the exception message to write to a log. The code look like:

if(IsWebApp)
{

    &

相关标签:
5条回答
  • 2021-01-18 02:54

    You can check to see if HttpContext.Current != null.

    0 讨论(0)
  • 2021-01-18 02:56

    I use the DomainManager type of Current AppDomain. MSDN documentation of AppDomainManager

    public static class AspContext
    {
        public static bool IsAspNet()
        {
            var appDomainManager = AppDomain.CurrentDomain.DomainManager;
            return appDomainManager != null && appDomainManager.GetType().Name.Contains("AspNetAppDomainManager");
        }
    }
    

    You can also check this other answer on SO

    0 讨论(0)
  • 2021-01-18 03:05

    How about

    If (Not System.Web.HttpContext.Current Is Nothing) Then
    
    End If
    

    or

    if(System.Web.HttpContext.Current != null){
    
    }
    
    0 讨论(0)
  • 2021-01-18 03:13

    Just check for some object that only exists in a web application, like HttpRuntime.AppVirtualPath that SLaks suggested.

    If it's a web application, you would still want to check if HttpContext.Current is null. If the exception occurs in code that is not run beacuse of a request, it doesn't have any context. The Session_OnEnd event for example runs when a server session is removed, so it doesn't have the context.

    0 讨论(0)
  • 2021-01-18 03:16

    Use the HttpRuntime class:

    if (!String.IsNullOrEmpty(HttpRuntime.AppDomainAppVirtualPath))
        //ASP.Net
    else 
        //Non-ASP.Net
    
    0 讨论(0)
提交回复
热议问题