简体   繁体   English

如何在asp.net C#中创建从URL获取参数的SQL查询#

[英]How can I create SQL Query which Takes Parameters from URL in asp.net C#

my link is like 我的链接就像

http://localhost/default.aspx?phone=9057897874&order=124556

Here Is my basic Page for passing Parameter In URL from ASP.net 这是我从ASP.net传递参数输入URL的基本页面

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"     Inherits="WebApplication2._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form method="get" action="default.aspx">

<label>Phone No</label>
<input type="text" name="phone" />
<br />
<label>Order No</label>
<input type="text" name="order" />
<br />
<input type="submit" value="submit" />
<br />
</form>

my c# file where I can store the prameters in Variables 我的c#文件,我可以在变量中存储参数

namespace WebApplication2
 {
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string strQuery;

        string phone = Request.QueryString["phone"];
        if (phone != null)
        {
            Response.Write("phone no is ");
            Response.Write(phone);
        }
        else

        {
            Response.Write("You phone number is not correct");
        }

        string order_no = Request.QueryString["order"];
        if (order_no != null)
        {
            Response.Write("Order No is ");
            Response.Write(order_no);
        }
        else
        {
            Response.Write("You Order number is not correct");
        }

//How I can Connect to Mysql Server

        strQuery = "SELECT order_status where orde01=''" + order_no + "'' and phone01=''" + phone + "''";

        Response.Write(strQuery);
}
}

I'm trying to doing something like this but it's only give me whole query as string. 我正在尝试做这样的事情,但它只给我整个查询作为字符串。 I am new on this topic. 我是这个话题的新手。 Any help will be appreciate Thanks 任何帮助将不胜感激谢谢

First off, concatenating a sql statement based on input that the user can change, especially when stored as a string is how SQL Injection Vulnerabilities are created. 首先,根据用户可以更改的输入连接sql语句,尤其是作为字符串存储时,SQL注入漏洞的创建方式。 Don't be that guy. 不要那个人。

as for tokenalizing your query string, use named parameters. 至于标记化查询字符串,请使用命名参数。 assume this is your query string 假设这是您的查询字符串

?orderid=777&phone=777-777-7777

Response.QueryString["orderid"] 

would return '777' and 将返回'777'和

Response.QueryString["phone"] 

woudl return '777-777-7777' woudl返回'777-777-7777'

as for your sql injection issue, you have a couple options. 至于你的SQL注入问题,你有几个选择。 one is a parameterized sql statement, see the C# example here: http://rosettacode.org/wiki/Parametrized_SQL_statement or use a stored procedure with parameters. 一个是参数化的sql语句,请参阅此处的C#示例: http//rosettacode.org/wiki/Parametrized_SQL_statement或使用带参数的存储过程。 the least desirable but minimally acceptable option is to regex validate your input parameters strictly, especially killing characters like '=;% -- and a few others. 最不可取但最低限度可接受的选项是正则表达式严格验证输入参数,特别是杀死'=;% - 和其他一些字符。

EDIT: now that I've had some time to work up a sample, check this out. 编辑:既然我有一些时间来处理样本,请检查一下。 This sample needs to be customized to your database, but its working on my mysql DB with a test table. 这个示例需要根据您的数据库进行自定义,但是它使用测试表处理我的mysql数据库。 you will need to install the MySQLConnector pack and add a project reference to 'MySql.Data' before the code will compile correctly. 在代码正确编译之前,您需要安装MySQLConnector包并添加项目引用“MySql.Data”。

namespace WebApplication2
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e) {
            //define some regex patterns for validating our data.
            const string PHONEREGEX = @"((\(\d{3}\))|(\d{3}-))\d{3}-\d{4}";
            const string ORDERNUMREGEX = @"\d*";

            bool isValid = true;

            string phone = Request.QueryString["phone"]; //read phone from querystring.

            //validate that arg was provided, and matches our regular expression. this means it contains only numbers and single hyphens
            if(!string.IsNullOrWhiteSpace(phone) && System.Text.RegularExpressions.Regex.IsMatch(phone, PHONEREGEX)){
                Response.Write(HttpUtility.HtmlEncode(string.Format("The phone number is {0}", phone))); //HTML Encode the value before output, to prevent any toxic markup.
            } else {
                Response.Write("Phone number not provided.");
                isValid = false;
            }

            string orderStr = Request.QueryString["order"]; //read ordernum from querystring
            long order = long.MinValue;

            //validate that order was provided and matches the regex meaning it is only numbers. then it parses the value into 'long order'.
            if(!string.IsNullOrWhiteSpace(orderStr) && System.Text.RegularExpressions.Regex.IsMatch(orderStr, ORDERNUMREGEX) && long.TryParse(orderStr, out order)){
                Response.Write(HttpUtility.HtmlEncode(string.Format("The order number is {0}", order))); //use 'long order' instead of orderStr.
            } else {
                Response.Write("Order number not provided.");
                isValid = false;
            }

            //if all arguments are valid, query the DB.
            if (isValid) {
                Response.Write(GetOrderStatus( phone, order));
            }

        }

        private static string GetOrderStatus(string phone, long order) {
            string status = "";

            //create a connection object
            string connstring = "SERVER=<YOUR MYSQL SERVER>;DATABASE=<YOUR DATABASE>;UID=<YOUR USER>;PASSWORD=<YOUR PASSWORD>-";//this is a connection string for mysql. customize it to your needs.
            MySql.Data.MySqlClient.MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection(connstring); //put your connection string in this constructor call 

            //create a SQL command object
            using (MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand()) { //use a using clause so resources are always released when done.
                cmd.Connection = conn;
                cmd.CommandText = "SELECT `Order_Status` FROM `<YOUR TABLE>` WHERE `Order` = @order AND `Phone` = @phone"; //this needs a From statement 

                //add parameters for your command. they fill in the @order and @phone in the sql statement above. customize these to match the data types in your database.
                cmd.Parameters.Add("order", MySql.Data.MySqlClient.MySqlDbType.Int64,11).Value = order; //do not use @ sign in parameter name
                cmd.Parameters.Add("phone", MySql.Data.MySqlClient.MySqlDbType.VarChar, 50).Value = phone;

                //execute the command, read the results from the query.
                cmd.Connection.Open();
                using (MySql.Data.MySqlClient.MySqlDataReader reader = cmd.ExecuteReader()) {
                    while (reader.Read()) {
                        status = reader.GetString("Order_Status");
                    }
                    cmd.Connection.Close();
                }

            }
            return status;
        }
    }
}

You should be using 你应该使用

Request.Form["phone"]
Request.Form["order"]

instead of 代替

Request.QueryString["phone"]
Request.QueryString["order"]

The reason for this is, you are doing a postback and never redirect to a url with those values set as a querystring 原因是,您正在进行回发并且永远不会重定向到具有设置为查询字符串的值的URL

However your question title would suggestion your have a url which contains something like 但是你的问题标题会暗示你有一个包含类似内容的网址

http://yourdomain.com?phone=0123456789&order=17 http://yourdomain.com?phone=0123456789&order=17

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM