c#get和post方式页面传值、接收的cs代码

用到两个 "Default2.aspx" 和 "Default3.aspx" 页,Default2.aspx页有"id=transBtn"的按钮控件,其点击事件为"protected void transBtn_Click(object sender, EventArgs e)"

1、GET方式:
(1)在Default2.aspx.cs 里的代码:
protected void transBtn_Click(object sender, EventArgs e)//用于测试的按钮
    {
       string url = "http://localhost:63419/WebSite2/Default3.aspx";
        string reqData = "UserName=admin&Password=123";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + (reqData == "" ? "" : "?") + reqData);
        request.Method = "GET";
        request.ContentType = "text/html;charset=UTF-8";
        //获取请求的响应
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream myResponseStream = response.GetResponseStream();
        StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
        string retStr = myStreamReader.ReadToEnd();
        myStreamReader.Close();
        myResponseStream.Close();
        response.Close();
        Response.Write(retstr);
    }
(2)在Default3.aspx.cs的代码:
protected void Page_Load(object sender, EventArgs e)
    {
        string result = "";
        string userName = Request.QueryString["UserName"];
        string password = Request.QueryString["Password"];
        if (userName == "admin" && password == "123")
        {   result = "登陆成功get"; }
        else
        { result = "登陆失败get";}
        Response.Write(result);
    }
2、POST方式:
(1)在Default2.aspx.cs 里的代码:
protected void transBtn_Click(object sender, EventArgs e)//用于测试的按钮
    {
       string url = "http://localhost:63419/WebSite2/Default3.aspx";
        string reqData = "UserName=admin&Password=123";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = reqData.Length;
        StreamWriter strWriter = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);
        strWriter.Write(reqData);
        strWriter.Flush();
        //获取请求的响应
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream myResponseStr = response.GetResponseStream();
        StreamReader reader = new StreamReader(myResponseStr, Encoding.GetEncoding("UTF-8"));
        string retStr = reader.ReadToEnd();
        reader.Close();
        myResponseStr.Close();
        response.Close();
        Response.Write("retStr")
    }
(2)在Default3.aspx.cs的代码:
protected void Page_Load(object sender, EventArgs e)
    {
        string result = "";
        string userName = Request.Form["UserName"];
        string password = Request.Form["Password"];
 
        if (userName == "admin" && password == "123")
        {  result = "登陆成功post";}
        else
        {result = "登陆失败post";}
        Response.Write(result);
    }

posted on 2016-06-23 17:20  小海很友爱  阅读(3128)  评论(0编辑  收藏  举报

导航