【问题标题】:How do I determine if the executing assembly is a web app or winform/console?如何确定正在执行的程序集是 Web 应用程序还是 winform/console?
【发布时间】:2010-04-16 15:03:50
【问题描述】:

我想编写一个辅助函数来构建异常消息以写入日志。 代码如下:

如果(IsWebApp)
{

使用 HttpContext 获取请求路径和 RawUrl }
其他
{
//否则它是一个winform/console
使用Assembly获取执行路径。

}

【问题讨论】:

    标签: .net asp.net c#-4.0


    【解决方案1】:

    使用HttpRuntime 类:

    if (!String.IsNullOrEmpty(HttpRuntime.AppDomainAppVirtualPath))
        //ASP.Net
    else 
        //Non-ASP.Net
    

    【讨论】:

    • +1 向我们其他人指出,并非 asp.net 中的所有内容都是请求线程 - 每天都学习新东西 :)
    【解决方案2】:

    只需检查一些仅存在于 Web 应用程序中的对象,例如 SLaks 建议的 HttpRuntime.AppVirtualPath

    如果它是一个 Web 应用程序,您仍然需要检查 HttpContext.Current 是否为空。如果异常发生在由于请求而未运行的代码中,则它没有任何上下文。例如,Session_OnEnd 事件在服务器会话被删除时运行,因此它没有上下文。

    【讨论】:

      【解决方案3】:

      您可以检查 HttpContext.Current != null 是否。

      【讨论】:

      • 错了。这将在 ASP.Net AppDomain 内的非请求线程中为空。
      【解决方案4】:

      怎么样

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

      if(System.Web.HttpContext.Current != null){
      
      }
      

      【讨论】:

      • 错了。这将在 ASP.Net AppDomain 内的非请求线程中为空。此外,VB.Net 有一个 IsNot 关键字。最后,他使用的是 C#。
      • 从来没有在这么短的时间内有这么多的错误!谢谢你让我们直截了当。我从 VB5 开始就一直在用 VB 编程,所以有时旧习惯很难改掉。这就是我将两者都包括在内的原因。
      【解决方案5】:

      我使用 DomainManager 类型的 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");
          }
      }
      

      您也可以查看this other answer on SO

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多