ASP.net: Programmatically Submit Form Post

On occasion it is necessary to post data via an HTTP POST to another page as though that post was submitted by a user but without the user’s interaction. In order to accomplish this use the following code:

        private void PostForm()

        {

            WebRequest request = WebRequest.Create(_targetUrl);

            request.Method = "POST";

            request.ContentType = "application/x-www-form-urlencoded";

            string postContent = string.Format("parameter1={0}&parameter2={1}", _parameter1, _parameter2);

            byte[] postContentBytes = Encoding.ASCII.GetBytes(postContent);

            request.ContentLength = postContentBytes.Length;

            Stream writer = request.GetRequestStream();

            writer.Write(postContentBytes, 0, postContentBytes.Length);

            writer.Close();

            HttpWebResponse testResponse = (HttpWebResponse)request.GetResponse();

            if (!testResponse.StatusDescription.Equals("OK", StringComparison.InvariantCultureIgnoreCase))

            {

                //TODO: Handle failure

            }

        }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s