如何确定执行的程序集是Web应用程序还是WinForm/控制台?

7
我想编写一个帮助函数,用于构建异常消息以写入日志。代码如下:
如果是Web应用程序:
{

      使用HttpContext获取请求路径和RawUrl
}
否则:
{
      //否则它是Winform/控制台
      使用Assembly获取执行路径。
}
5个回答

12

使用 HttpRuntime 类:

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

+1 是指出了对我们所有人来说,不是所有的asp.net都是请求线程 - 每天学点新东西 :) - Ray

1

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

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


0

我使用当前应用程序域的DomainManager类型。AppDomainManager的MSDN文档

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

你也可以查看这个SO上的其他答案


0

如何呢?

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

End If

或者

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

}

1
错误。在ASP.Net AppDomain内的非请求线程中,这将为空。此外,VB.Net有一个“IsNot”关键字。最后,他正在使用C#。 - SLaks
从来没有这么多人在如此短的时间内如此错误!感谢您纠正我们。 我一直在使用VB编程,自VB5以来,有时候老习惯难改。 这就是为什么我包含了两者。 - Jeremy

0

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


2
错误。在 ASP.Net AppDomain 内的非请求线程中,这将为 null。 - SLaks

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接