接受参数的Request为什么会经常报错,未将对象的引用设置到对象实例

无论是get,还是post,都可以用Request[""]来获取,但是有时候会报错——未将对象的引用设置到对象实例,有时候又正常,到底怎么回事

if(!string.IsNullOrEmpty(Request["id"].ToString()))

{

}

这个一般情况下都是没问题的,因为,基本上都可以转换成string

if (!string.IsNullOrEmpty(Request.UrlReferrer.ToString()))
{
string refer = HttpContext.Current.Request.UrlReferrer.ToString();
}

这样写的话,如果它没有refer的话,那肯定就会报错的,原因很简单了:

因为Request.UrlReferrer为null,此时在转换成ToString()就一定会报错了

所以,为了安全保证,我们一般都这样判断

if (!string.IsNullOrEmpty(Request.UrlReferrer))
{
string refer = HttpContext.Current.Request.UrlReferrer.ToString();
}

 

if (!string.IsNullOrEmpty(Request["xx"]))
{
string refer = Request["xx"].ToString();
}

这样就万无一失了,哈哈

posted on 2017-04-07 18:24  奔游浪子  阅读(422)  评论(0)    收藏  举报

导航