[英]Null reference exception in foreach (string var in Request.QueryString)
I tried to find a solution for this question, but with no success... I tried to remove .ToString() from Request.QueryString[var] and to add an if control at the beginning like this 我试图为这个问题找到解决方案,但没有成功...我试图从Request.QueryString [var]中删除.ToString(),并像这样在开头添加一个if控件。
if Request.QueryString.HasKeys()) {
foreach (string var in Request.QueryString)
{.........
.............
}
but nothing.... 但是什么都没有。
The complete code is 完整的代码是
string[] array_split_item = new string[] {"<script", "</script>", "‘", "’" };
int pos = 0;
string strReq = "";
foreach (string var in Request.QueryString)
{
foreach (string strItem in array_split_item)
{
strReq = Request.QueryString[var].ToString();
pos = strReq.ToLower().IndexOf(strItem.ToLower()) + 1;
if (pos > 0)
{
Response.Write("Some Text");
Response.End();
}
}
}
Why this exception? 为什么会有这个例外?
Thanks 谢谢
you can't foreach through Request.QueryString like that. 你不能像这样通过Request.QueryString foreach。
Try this (not tested) 试试看(未测试)
foreach (string KEY in Request.QueryString.Keys)
{
string value = Request.QueryString[KEY]; //already a string by design, no need to ToString() it
// ... use value for whatever you need
}
EDIT: visual studio 2008 builds this fine (pasted into the page_load method of an ASPX page to try it); 编辑: Visual Studio 2008构建良好(粘贴到ASPX页的page_load方法中进行尝试); Visual Studio 2010 SP1 doesn't complain either upoon building.
Visual Studio 2010 SP1不会抱怨任何更新。
string[] array_split_item = new string[] { "<script", "</script>", "‘", "’" };
int pos = 0;
string strReq = "";
foreach (string var in Request.QueryString.Keys)
{
foreach (string strItem in array_split_item)
{
strReq = Request.QueryString[var].ToString();
pos = strReq.ToLower().IndexOf(strItem.ToLower()) + 1;
if (pos > 0)
{
Response.Write("Some Text");
Response.End();
}
}
}
There must be something wrong somewhere else in the code i think. 我认为代码中的其他地方肯定有问题。
I beleive it may be because you're using the value of a key in QueryString to access a value. 我相信这可能是因为您正在使用QueryString中的键值来访问值。 Try changing the line
strReq = Request.QueryString[var].ToString();
尝试更改以下行
strReq = Request.QueryString[var].ToString();
to 至
strReq = var.ToString();
You are naming your string var which is also a type. 您正在命名字符串var,它也是一种类型。 Replace var with another name.
用其他名称替换var。
foreach (string text in Request.QueryString.Keys)
.....
strReq = Request.QueryString[text].ToString();
You should use Request.QueryString.Keys
to loop on the QueryString: 您应该使用
Request.QueryString.Keys
在QueryString上循环:
foreach (string key in Request.QueryString.Keys)
{
string value = Request.QueryString[key];
if (!String.IsNullOrEmpty(value))
{
//do work
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.