首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >检查空后的System.NullReferenceException

检查空后的System.NullReferenceException
EN

Stack Overflow用户
提问于 2014-07-18 10:35:34
回答 1查看 456关注 0票数 0

我有一个简单的函数来记录在显示某些页面时可能发生的错误。我使用空合并操作符来确保我的string.Format中没有任何string.Format。

错误: System.NullReferenceException:对象引用没有设置为对象的实例。在ASP._core_showad_aspx.LogError(String sType,String sIP,Nullable1 id, Nullable1 id2)

代码语言:javascript
运行
复制
void LogError(string sType, string sIP, int? id, int? id2)
{
    string error   =   string.Format("'{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', '{9}', '{10}', '{11}'", 
    sType??"", sIP??"", id??-1, id2??-1, 
    Request.ServerVariables["HTTP_X_ORIGINAL_URL"]??"", Request.ServerVariables["URL"]??"", Request.ServerVariables["QUERY_STRING"]??"", 
    Request.Path??"", Request.ServerVariables["HTTP_REFERER"]??"", Request.ServerVariables["HTTP_USER_AGENT"]??"", 
    Request.ServerVariables["REMOTE_HOST"]??"", Request.ServerVariables["HTTP_COOKIE"].Substring(0, (Request.ServerVariables["HTTP_COOKIE"].Length>399)?399:Request.ServerVariables["HTTP_COOKIE"].Length)??"");

    WriteLog(error);
}

空合并操作符不应该阻止这种情况发生吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-07-18 10:37:34

您的Request.ServerVariables["HTTP_COOKIE"]不检查null。

试试这个:

代码语言:javascript
运行
复制
string httpCookie = string.Empty;
if (Request.ServerVariables["HTTP_COOKIE"] != null)
{
   httpCookie = Request.ServerVariables["HTTP_COOKIE"].Substring(0, (Request.ServerVariables["HTTP_COOKIE"].Length>399)?399:Request.ServerVariables["HTTP_COOKIE"].Length)
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24823007

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档