Jul 15, 2010

Submit ASP.NET Form quickly from C# app using Fiddler

The easiest way to see browser server interaction is to use a tool like Fiddler, which shows every request and response between your machine and a web server. It allows to inspect all http(s) traffic, set breakpoints. Generally, it is required to submit web form programmatically and for this, we must know about http request/response format for the web page. Here is simple example to submit asp.net web form from C# windows app with the help of Fiddler.

In the example, there is textbox for name. If user enters Brij, It shows ‘Welcome Brij’ as response else it gives authorization error message.


<form id="form1" runat="server"> 
         Your Name: <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
         <asp:button runat="server" text="OK" ID="btnOK" onclick="btnOK_Click" />
</form>

protected void btnOK_Click(object sender, EventArgs e)
    {
        if (txtName.Text == "Brij")
        {
            txtName.Visible = false;
            btnOK.Visible = false; 
            Response.Write("Welcome Brij");
        }
        else
        {
            Response.Write("You are not authorize to run this app.");  
        }
    }

1. Open this page in browser and make sure, it shows welcome message on entering Brij.

2. Open fiddler, type the page link in left bottom textbox and press enter. It will open link in browser, Enter name in textbox and click on OK button. Then go to fiddler, See the Inspector tab.

fiddler

I get following thing:

__VIEWSTATE=%2FwEPDwULLTE0MDM4MzYxMjNkZH%2FNwkP9gKqO49Tjfut8xnCvul1y&__EVENTVALIDATION=%2FwEWAwKjsum6CQLEhISFCwLdkpmPAZBBqk0kyAujA81fN7IgMyQE4bJp&txtName=brij&btnOK=OK

There are 4 parameters:

__VIEWSTATE

__EVENTVALIDATION

txtName

btnOK

You can see these parameters in view source of the page.

3. Create a new c# windows app, Drag a textbox(txtName) and button and write following code on button click:


            byte[] response;
            String testURL = "http://brijserver/fiddler/default.aspx";
            WebClient webClient = new WebClient();
            response = webClient.DownloadData(testURL); 
            string postData = String.Format(
               "__VIEWSTATE=%2FwEPDwULLTE0MDM4MzYxMjNkZH%2FNwkP9gKqO49Tjfut8xnCvul1y&__EVENTVALIDATION=%2FwEWAwKjsum6CQLEhISFCwLdkpmPAZBBqk0kyAujA81fN7IgMyQE4bJp&txtName={0}&btnOK=OK",
               txtName.Text);
            webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            response = webClient.UploadData(testURL, "POST", Encoding.ASCII.GetBytes(postData));
            string ret = Encoding.ASCII.GetString(response);
            MessageBox.Show(ret.Substring(0,ret.IndexOf(Environment.NewLine))); 

In postdata, I used copied string from fiddler and replaced txtName value to windows app textbox(txtName) text.

Now If I enter suresh in textbox

fiddler

and get following on entering Brij

post form

Hope! It helps.