Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# HttpContext.Current对于机器人程序为空_C#_Asp.net_C# 4.0 - Fatal编程技术网

C# HttpContext.Current对于机器人程序为空

C# HttpContext.Current对于机器人程序为空,c#,asp.net,c#-4.0,C#,Asp.net,C# 4.0,在由.NET页面调用的类中,我有以下代码(页面加载事件期间asp.NET webforms): 这一行为任何机器人抛出一个异常:googlebot、bingbot等 例外情况是:对象引用未设置为对象的实例,并且位于get访问器行上。它看起来像HttpContext。当前值为空。您应该检查会话中的null如下所示: public static bool BrowserSupportsJS { get { if(HttpContext.Current.Session =

在由.NET页面调用的类中,我有以下代码(页面加载事件期间asp.NET webforms):

这一行为任何机器人抛出一个异常:googlebot、bingbot等


例外情况是:对象引用未设置为对象的实例,并且位于get访问器行上。它看起来像HttpContext。当前值为空。

您应该检查
会话
中的
null
如下所示:

public static bool BrowserSupportsJS
{
   get 
   { 
       if(HttpContext.Current.Session == null)
           return false;
       return (HttpContext.Current.Session["js_support"] != null 
           && ((bool)HttpContext.Current.Session["js_support"]));

   }
}

为什么不在访问HttpContext.Current之前检查它是否为null?没错。只需检查它是否为null,并返回false即可。@GeorgeJohnston我怀疑在收到http请求时执行的代码中,
HttpContext.Current
是否为null。更可能是
Session
,因为它依赖于机器人通常不支持的会话cookie。是否确定它不是
Session
that
null
?我无法想象在没有上下文的情况下运行asp.net代码。另一方面,我可以很好地想象会话可能无法设置(尽管我以前从未寻找过这种行为)。我认为他的问题是
为什么
而不是
如何修复它
修复它真的很容易,但一个请求怎么可能是空的
httpcontext
public static bool BrowserSupportsJS
{
   get 
   { 
       if(HttpContext.Current.Session == null)
           return false;
       return (HttpContext.Current.Session["js_support"] != null 
           && ((bool)HttpContext.Current.Session["js_support"]));

   }
}