【发布时间】:2010-04-16 15:03:50
【问题描述】:
我想编写一个辅助函数来构建异常消息以写入日志。 代码如下:
如果(IsWebApp)
{
使用 HttpContext 获取请求路径和 RawUrl
}
其他
{
//否则它是一个winform/console
使用Assembly获取执行路径。
}
【问题讨论】:
我想编写一个辅助函数来构建异常消息以写入日志。 代码如下:
如果(IsWebApp)
{
使用 HttpContext 获取请求路径和 RawUrl
}
其他
{
//否则它是一个winform/console
使用Assembly获取执行路径。
}
【问题讨论】:
使用HttpRuntime 类:
if (!String.IsNullOrEmpty(HttpRuntime.AppDomainAppVirtualPath))
//ASP.Net
else
//Non-ASP.Net
【讨论】:
只需检查一些仅存在于 Web 应用程序中的对象,例如 SLaks 建议的 HttpRuntime.AppVirtualPath。
如果它是一个 Web 应用程序,您仍然需要检查 HttpContext.Current 是否为空。如果异常发生在由于请求而未运行的代码中,则它没有任何上下文。例如,Session_OnEnd 事件在服务器会话被删除时运行,因此它没有上下文。
【讨论】:
您可以检查 HttpContext.Current != null 是否。
【讨论】:
怎么样
If (Not System.Web.HttpContext.Current Is Nothing) Then
End If
或
if(System.Web.HttpContext.Current != null){
}
【讨论】:
IsNot 关键字。最后,他使用的是 C#。
我使用 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
【讨论】: