Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/187.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在asp.net C中创建从URL获取参数的SQL查询#_C#_Asp.net_Sql Server - Fatal编程技术网

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

C# 如何在asp.net C中创建从URL获取参数的SQL查询#,c#,asp.net,sql-server,C#,Asp.net,Sql Server,我的链接就像 http://localhost/default.aspx?phone=9057897874&order=124556 这是我从ASP.net在URL中传递参数的基本页面 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication2._Default" %> <!DOCTYPE html PUBLIC "-/

我的链接就像

http://localhost/default.aspx?phone=9057897874&order=124556
这是我从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>
我正在尝试这样做,但它只是将整个查询作为字符串提供给我。 我对这个话题不熟悉。 任何帮助都将不胜感激 谢谢

您应该使用

Request.Form["phone"]
Request.Form["order"]
而不是

Request.QueryString["phone"]
Request.QueryString["order"]
这样做的原因是,您正在进行回发,并且从不重定向到那些值设置为查询字符串的url

然而,你的问题标题会建议你有一个包含如下内容的url


首先,根据用户可以更改的输入连接sql语句,尤其是当存储为字符串时,是创建sql注入漏洞的方式。别做那个家伙

至于标记查询字符串,请使用命名参数。假设这是您的查询字符串

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

Response.QueryString["orderid"] 
将返回“777”和

Response.QueryString["phone"] 
woudl返回“777-777-7777”

至于sql注入问题,您有两个选择。一个是参数化sql语句,请参见此处的C#示例: 或者使用带参数的存储过程。最不理想但最低限度可接受的选项是正则表达式严格验证输入参数,特别是删除“=;%”等字符还有其他一些

编辑:现在我有时间准备一个样本,看看这个。这个示例需要根据您的数据库进行定制,但它使用的是我的mysql数据库和一个测试表。在代码正确编译之前,您需要安装包并添加对“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;
        }
    }
}
命名空间WebApplication2
{
公共部分类\u默认值:System.Web.UI.Page
{
受保护的无效页面加载(对象发送方、事件参数e){
//定义一些用于验证数据的正则表达式模式。
常量字符串PHONEREGEX=@“(\(\d{3}\))|(\d{3}-)\d{3}-\d{4}”;
常量字符串ORDERNUMREGEX=@“\d*”;
bool isValid=true;
string phone=Request.QueryString[“phone”];//从QueryString读取电话。
//验证是否提供了arg,并与正则表达式匹配。这意味着它只包含数字和单连字符
if(!string.IsNullOrWhiteSpace(phone)和&System.Text.RegularExpressions.Regex.IsMatch(phone,PHONEREGEX)){
Response.Write(HttpUtility.HtmlEncode(string.Format(“电话号码是{0}”,phone));//HTML在输出前对值进行编码,以防止任何有毒标记。
}否则{
回复。写下(“未提供电话号码”);
isValid=false;
}
string orderStr=Request.QueryString[“order”];//从QueryString读取ordernum
long order=long.MinValue;
//验证是否提供了顺序并与正则表达式匹配,这意味着它只是数字。然后将值解析为“长顺序”。
if(!string.IsNullOrWhiteSpace(orderStr)和&System.Text.RegularExpressions.Regex.IsMatch(orderStr,ORDERNUMREGEX)和&long.TryParse(orderStr,out order)){
Response.Write(HttpUtility.HtmlEncode(string.Format(“订单号为{0}”,order));//使用'long order'代替orderStr。
}否则{
回复。填写(“未提供订单号”);
isValid=false;
}
//如果所有参数都有效,则查询数据库。
如果(有效){
Write(GetOrderStatus(电话、订单));
}
}
私有静态字符串GetOrderStatus(字符串电话,长订单){
字符串状态=”;
//创建一个连接对象
string connstring=“SERVER=;DATABASE=;UID=;PASSWORD=-”;//这是mysql的连接字符串。请根据需要自定义它。
MySql.Data.MySqlClient.MySqlConnection conn=new MySql.Data.MySqlClient.MySqlConnection(connstring);//将连接字符串放入此构造函数调用中
//创建SQL命令对象
using(MySql.Data.MySqlClient.MySqlCommand cmd=new MySql.Data.MySqlClient.MySqlCommand()){//请使用using子句,以便在完成时始终释放资源。
cmd.Connection=conn;
cmd.CommandText=“从`WHERE`Order`=@Order和`Phone`=@Phone`中选择`Order\\u Status`FROM`///这需要一个FROM语句
//为您的命令添加参数。它们在上面的sql语句中填写@order和@phone。自定义这些参数以匹配数据库中的数据类型。
cmd.Parameters.Add(“order”,MySql.Data.MySqlClient.MySqlDbType.Int64,11)。Value=order;//不要使用@sign-in参数名
cmd.Parameters.Add(“phone”,MySql.Data.MySqlClient.MySqlDbType.VarChar,50).Value=phone;
//执行命令,从查询中读取结果。
cmd.Connection.Open();
使用(MySql.Data.MySqlClient.MySqlDataReader=cmd.ExecuteReader()){
while(reader.Read()){
status=reader.GetString(“订单状态”);
}
cmd.Connection.Close();
}
}
返回状态;
}
}
}

这里要特别小心,您应该真正了解哪些代码容易受到攻击!简而言之,使用参数可以避免这种情况,不要将查询写成那样的字符串。@user1778175您在这里问错了问题。您想问
如何从c#连接到?
@Biff MaGriff:What do You mean。?我还建议使用.NET的内置控件,如asp:TextBox,而不是经典的html表单元素。然后可以作为txtPhone.Text访问。然后使用SQL参数而不是SQL连接来防止像Frank建议的那样的注入攻击。嗨,谢谢你能提供任何代码作为查询的示例,我可以将查询值存储在字符串中并显示在同一页面中哇,实际上这也是一个问题。信息技术
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;
        }
    }
}