我有一个简单的函数来记录在显示某些页面时可能发生的错误。我使用空合并操作符来确保我的string.Format中没有任何string.Format。
错误: System.NullReferenceException:对象引用没有设置为对象的实例。在ASP._core_showad_aspx.LogError(String sType,String sIP,Nullable
1 id, Nullable
1 id2)
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);
}
空合并操作符不应该阻止这种情况发生吗?
发布于 2014-07-18 10:37:34
您的Request.ServerVariables["HTTP_COOKIE"]
不检查null。
试试这个:
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)
}
https://stackoverflow.com/questions/24823007
复制相似问题