开发者

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 ad开发者_如何学编程d an if control at the beginning like this

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.

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 2010 SP1 doesn't complain either upoon building.

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. Try changing the line strReq = Request.QueryString[var].ToString(); to

strReq = var.ToString();


You should use Request.QueryString.Keys to loop on the QueryString:

foreach (string key in Request.QueryString.Keys)
{
    string value = Request.QueryString[key];
    if (!String.IsNullOrEmpty(value))
    {
        //do work
    }
}


You are naming your string var which is also a type. Replace var with another name.

foreach (string text in Request.QueryString.Keys)
.....
strReq = Request.QueryString[text].ToString();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜