我想编写一个帮助函数,用于构建异常消息以写入日志。代码如下:
如果是Web应用程序:
{
使用HttpContext获取请求路径和RawUrl
}
否则:
{
//否则它是Winform/控制台
使用Assembly获取执行路径。
}
如果是Web应用程序:
{
使用HttpContext获取请求路径和RawUrl
}
否则:
{
//否则它是Winform/控制台
使用Assembly获取执行路径。
}
使用 HttpRuntime 类:
if (!String.IsNullOrEmpty(HttpRuntime.AppDomainAppVirtualPath))
//ASP.Net
else
//Non-ASP.Net
只需检查一些仅存在于Web应用程序中的对象,例如SLaks建议的HttpRuntime.AppVirtualPath
。
如果是Web应用程序,则仍要检查HttpContext.Current
是否为空。如果异常发生在未运行请求的代码中,则没有任何上下文。例如,Session_OnEnd事件在删除服务器会话时运行,因此它没有上下文。
我使用当前应用程序域的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上的其他答案
如何呢?
If (Not System.Web.HttpContext.Current Is Nothing) Then
End If
或者
if(System.Web.HttpContext.Current != null){
}
您可以检查HttpContext.Current != null。