This is just a small example how to use WebRequest and how to respond to it from an aspx page. Of course you could send your request to any other page which accepts POST requests. I have created a web application to test this behaviour as I will need it later in my project. There are some things you will need to watch out for. I've spent some time searching for the answers so hopefully you won't have to.

Step 1: Create a new web application and in the project properties set it so it runs on specific port. In my case I set it to port 45000. It is important for testing as when you use WebRequest.Create method, you must specify the URI exactly.

Step 2: Now setup your default.aspx with two textboxes - this is for the parameters you will be passing and two labels which will display the result of the webrequest.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Text 1
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        &nbsp;&nbsp;Text 2
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        &nbsp;<asp:Button ID="Button1" runat="server" Text="Post" OnClick="Button1_Click" />
        <br />
        <br />
        <br />
        Received Status:
        <asp:Label ID="Label1" runat="server"></asp:Label>
        <br />
        Received Response:
        <asp:Label ID="Label2" runat="server"></asp:Label>
    </div>
    </form>
</body>
</html>


Step 3: Setup a page which we are going to target. Something like CreateResponse.aspx. This page will do absolutely nothing only respond to your request so remove all the code after %>

This is important if you want to create responses to your requests ("Response.Write") and don't want to worry about the entire html it will return.

If you leave the <form> tag inside this page you may come across the following error after calling this page more than once.

The state information is invalid for this page and might be corrupted.

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CreateResponse.aspx.cs" Inherits="WebApplication1.CreateResponse" %>

 

Step 4: Write code behind the response page to do something. Notice the StatusDescription property it will work correctly only if you run your web application on IIS server. If you run this on VS development server it will always return default StatusDescription - OK.

using System;
using System.Net;
using System.Web;

namespace WebApplication1
{
    public partial class CreateResponse : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string strText1 = "";
            string strText2 = "";

            try
            {
                if (!string.IsNullOrEmpty(this.Request.QueryString["text1"].ToString()))
                {
                    strText1 = this.Request.QueryString["text1"].ToString();
                }
            }
            catch { }

            try
            {
                if (!string.IsNullOrEmpty(this.Request.QueryString["text2"].ToString()))
                {
                    strText2 = this.Request.QueryString["text2"].ToString();
                }
            }
            catch { }

            if (strText1 != "" || strText2 != "")
            {
                Response.StatusDescription = "Ok - got vars";
                Response.Write("Got this: - " + strText1 + " - " + strText2);
            }
            else
            {
                Response.StatusDescription = "Error - no vars";
                Response.Write("Got nothing at all");
            }
        }
    }
}

 

 

Step 5: And finally here is the code for you default.aspx page to create webrequest call.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Net;
using System.IO;


namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string strText1 = HttpUtility.UrlEncode(TextBox1.Text);
            string strText2 = HttpUtility.UrlEncode(TextBox2.Text);

            string strParams = "text1=" + strText1 + "&text2=" + strText2;

            // Create a request using a URL that can receive a post.
            WebRequest request = WebRequest.Create("http://localhost:45000/CreateResponse.aspx?" + strParams);
            request.Method = "POST";
            string postData = "";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();


            // Get the response.
            WebResponse response = request.GetResponse();           
            // Display the status.
            Label1.Text = ((HttpWebResponse)response).StatusDescription;
            // Get the stream containing content returned by the server.
            dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream,Encoding.ASCII);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            Label2.Text = responseFromServer;
            // Clean up the streams.
            reader.Close();
            dataStream.Close();
            response.Close();
        }
    }
}

 

Here is the source code for the above example...

WebApplication1.zip (153.80 kb)