提前搜索 - 网址编码

时间:2012-07-26 21:38:53

标签: c# asp.net

我有一个非常奇怪的问题,我不知道如何摆脱这个。

我有一个提前搜索我的项目,它基本上是学校搜索

我的问题是我使用LIKE来比较该选项,在搜索结束时,我的查询应如下所示:

select *
from tbl_schooldetails
where
  state = 'Gujarat'
  and city = 'Ahmedabad'
  and area = 'Navrangpura'
  and ( board = 'xx' or board LIKE '%CBSE Board%' or board LIKE '%Gujarat Board%')

但我得到以下查询:

select *
from tbl_schooldetails
where
  state = 'Gujarat'
  and city = 'Ahmedabad'
  and area = 'Navrangpura'
  and ( board = 'xx' or board LIKE '�SE Board%' or board LIKE '%Gujarat Board%')

如果您发现我的%CB已转换为“ ”符号,那么我无法搜索与“CBSE Board”选项相关的任何结果。

有谁能告诉我如何摆脱这种URL编码?

这是我生成此查询的代码:

  string qry = "select * from tbl_schooldetails where state = '" + sdpd4.SelectedItem.Text + "'";

    if (sdpd2.SelectedItem.Text != "Select City")
    {
        qry += " and city = '" + sdpd2.SelectedItem.Text + "'";
    }

    if (sdpd1.SelectedItem.Text != "Select Area")
    {
        qry += " and area = '" + sdpd1.SelectedItem.Text + "'";
    }

    if (CheckBoxList3.SelectedItem != null)
    {
        qry = qry + " and ( board = 'xx'";

          for (int i = CheckBoxList3.Items.Count - 1; i >= 0; i--)
          {
              if (CheckBoxList3.Items[i].Selected == true)
              {

                  string mt = CheckBoxList3.Items[i].ToString();
                  qry = qry + " or board LIKE '" + '%' + mt + '%' + "'";

              }
          }
            qry = qry + ")";
    }


    if (RadioButtonList1.SelectedItem != null)
    {
        qry += " and gender ='" + RadioButtonList1.SelectedItem.Text + "'";
    }



    Response.Redirect("schoolsearchresult2.aspx?search=" + qry);

2 个答案:

答案 0 :(得分:4)

已编辑,现在原来的问题更清晰了。

只需改变一下:

Response.Redirect("schoolsearchresult2.aspx?search=" + qry);

对此:

Response.Redirect("schoolsearchresult2.aspx?search=" 
    + HttpServerUtility.UrlEncode(qry));

...但是:我的警告(以及其他所有人)仍然正确:在查询字符串中传递WHERE子句非常危险 - 对结果进行微不足道的调整URL可以 销毁您的数据库。

原始回答

您似乎将%CB放入一个URL,该URL在服务器上被解释为十六进制数字。

如果您使用%25CB,则应将其解释为“%CB”。

或者,您可以使用其中一个内置c#函数。我认为你需要的是HttpServerUtility.UrlEncode

非常重要:

如果这是一个真实的应用程序,而不是概念验证项目,you must not copy data directly from the URL into your SQL string!

答案 1 :(得分:0)

我建议你以这种方式构建你的sql查询,这样你就不用担心url编码和Sql注入

string sqlQuery = "select *
from tbl_schooldetails
where
  state = @state
  and city = @city
  and area = @area
  and ( board = @board1 or board LIKE ";
 sqlQuery += "%@board2%";
sqlQuery += " or board LIKE %@board3%");

然后在执行查询时使用

e.g。

SqlCommand cmd = new SqlCommand(command);
cmd.Parameters.AddWithValue("@state", Request.Form["state"]);

......等等