.Net中利用WebClient,HttpWebRequest,HttpWebResponse等,模拟Http POST请求,并检查Response回来的数据,对请求的执行结果做简单的判断,看是否和预期值相同。作为web自动测试和web安全测试框架的一个基础代码。

        在ASP2.0中需要加入ViewState和EventValidation,最开始是用Fiddler或者TramperIE去截一次Request或者直接去页面上取,后来改进后,用WebClient自动去获取,并转成URL编码(十六进制)。

//03 发送Http POST请求给ASP.Net
//default.aspx     ASP.Net 2.0

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>无标题页</title>
</head>
<body>
<script language="C#" runat="server">
    void Button1_Click(Object sender, System.EventArgs e)
    {
        if (TextBox1.Text == "red")
            TextBox2.Text = "Roses are red";
        else if (TextBox1.Text == "blue")
            TextBox2.Text = "The Sky is blue";
        else
            TextBox2.Text = "Unknow color";
         
    }
   
      </script>
      <h3>Color Commenter</h3>
    <form id="form1"  method="post"  runat="server">
    <p>Enter Color:
          <asp:TextBox ID="TextBox1" runat="server" />
    </p>
    <p>Mycomment:
          <asp:TextBox ID="TextBox2" runat="server" />
    </p>
   <p><asp:Button ID="Button1" Text="Send" OnClick="Button1_Click" runat="server" />
   </p>
    </form>
</body>
</html>


//Program.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Diagnostics;
using System.Web;


namespace WebTest
{
    class Program
    {
        private static string ViewState(string uri)
        {
            try
            {
                WebClient wc = new WebClient();
                Stream st = wc.OpenRead(uri);
                StreamReader sr = new StreamReader(st);
                string res = sr.ReadToEnd();
                sr.Close();
                st.Close();
                int start = res.IndexOf("__VIEWSTATE", 0) + 37;
                //如果是针对asp.net1.1,只需要把37改成20,另外POST上也不需要EventValidation
                int end = res.IndexOf("\"", start);
                string vs = res.Substring(start, (end - start));
                return vs;
            }
            catch
            {
                throw new Exception("Fatal error finding ViewState");
            }
        }

        private static string EventValidation(string uri)
        {
            try
            {
                WebClient wc = new WebClient();
                Stream st = wc.OpenRead(uri);
                StreamReader sr = new StreamReader(st);
                string res = sr.ReadToEnd();
                sr.Close();
                st.Close();
                int start = res.IndexOf("__EVENTVALIDATION", 0) + 49;
                int end = res.IndexOf("\"", start);
                string ev = res.Substring(start, (end - start));
                return ev;
            }
            catch
            {
                throw new Exception("Fatal error finding EventValidation");
            }
        }

          
        static void Main(string[] args)
        {
            string url = "http://localhost:14169/WebExam/Default.aspx";
            string data = "TextBox1=blue&TextBox2=empty&Button1=clicked";
           
            string vs = HttpUtility.UrlEncode(ViewState(url));//
            Console.WriteLine("\nViewState: \n "+vs);
            string ev = HttpUtility.UrlEncode(EventValidation(url));
             Console.WriteLine("\nEventValidation: \n"+ev+"\n\n\n");

           /*
            WebClient wc = new WebClient();
            Stream st = wc.OpenRead(url);
            StreamReader sr = new StreamReader(st);
            string res = sr.ReadToEnd();
            Console.WriteLine(res);
            sr.Close();
            sr.Close();
           
            //asp.net 1.1
            int start = res.IndexOf("__VIEWSTATE", 0) + 20;
            int end = res.IndexOf("\"", start);
            string vs = res.Substring(start, (end - start));
            Console.WriteLine("ViewState = " + vs);
           

            //asp.net 2.0
            //使用WebClient对象发送一个简单的、试探性的HTTP请求给待测程序,取回HTTP Response
            int startVS = res.IndexOf("__VIEWSTATE", 0) + 37;
            int endVS = res.IndexOf("\"", startVS);
            string vs = res.Substring(startVS, (endVS - startVS));
            Console.WriteLine("ViewState = " + vs);
            int startEV = res.IndexOf("__EVENTVALIDATION", 0) + 49;
            int endEV = res.IndexOf("\"", startEV);
            string ev = res.Substring(startEV, (endEV - startEV));
            Console.WriteLine("EventValidation = " + ev);
            */
                       
           //string vs = "%2FwEPDwUJMzQ3NzYxOTc5ZGQP%2Fqne%2FF21jnuqNVpbVe7grlKrXg%3D%3D";
           //基于asp2.0的需要把eventvalidation值加上
           //string eventvalidation = "%2FwEWBALylePmAwLs0bLrBgLs0fbZDAKM54rGBmAyxjYUo1p7M7SV%2FjEpIryiqnaR";
           data = "__VIEWSTATE=" + vs +"&"+data+ "&__EVENTVALIDATION="+ev;
           byte[] buffer = Encoding.ASCII.GetBytes(data);

           HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
           req.Method = "POST";
           req.ContentType = "application/x-www-form-urlencoded";
           req.ContentLength = buffer .Length;

           Stream reqst = req.GetRequestStream();
           reqst.Write(buffer,0,buffer.Length);
           reqst.Flush();
           reqst.Close();

           HttpWebResponse res = (HttpWebResponse)req.GetResponse();
           Stream resst = res.GetResponseStream();
           StreamReader sr = new StreamReader(resst);
           string str = sr.ReadToEnd();
           Console.WriteLine(str);
           Console.WriteLine("\n\n\n");

            //通过检查预期结果,判断是否正确。
           int intStart = str.IndexOf("Roses are red", 0);
           Console.WriteLine(intStart);
           if (intStart != -1)
           {
               string result = str.Substring(intStart, 13);
               Console.WriteLine(result);
           }
           else
               Console.WriteLine("结果不正确!\n");


           sr.Close();
           resst.Close();
          

        }
    }
}
 



本文链接地址:http://www.bzcyer.com/post/104.html

----------------------------------------------------------------------------------------------------