Wednesday 26 August 2015

Post data to web and display on web form in ASP.NET C#

There are few basic points which describe how to post request data to web getpostdata.aspx and how to consume those data on web getpostdata.aspx.

Step 1. Create a method that allow to post data

  1. Define the URL where we have to post data
  2. Set the Method property of the request to POST.
  3. Create a request using a URL that can receive a post. 
  4. Create POST data and convert it to a byte array.
  5. Set the ContentType property of the WebRequest.
  6. Set the ContentLength property of the WebRequest.
  7. Get the request stream.
  8. Write the data to the request stream.
  9. Close the Stream object.
  10. Get the response.
  11. Display the status.
  12. Get the stream containing content returned by the server.
  13. Open the stream using a StreamReader for easy access.
  14. Read the content.
  15. Display or retun the content.
  16. Clean up the streams.


  public static string GetContentFomWeb(string csr)
        {
            try
            {
                //1
                WebRequest request = WebRequest.Create("http://beta.example.com/work/getpostdata.aspx");
                //2
                request.Method = "POST";
                //3
                var formdata ="csr=" + csr ;
                //4
                byte[] byteArray = UTF8Encoding.ASCII.GetBytes(formdata.ToString());
                //5
                request.ContentType = "application/x-www-form-urlencoded";
                //6
                request.ContentLength = byteArray.Length;
                //7
                Stream dataStream = request.GetRequestStream();
                //8
                dataStream.Write(byteArray, 0, byteArray.Length);
                //9
                dataStream.Close();
                //10
                WebResponse response = request.GetResponse();
                //11
                //Console.WriteLine(((HttpWebResponse)response).StatusDescription);
                //12
                dataStream = response.GetResponseStream();
                //13
                StreamReader reader = new StreamReader(dataStream);
                //14
                string responseFromServer = reader.ReadToEnd();
                //15
                reader.Close();
                dataStream.Close();
                response.Close();
                return responseFromServer;

            }
            catch(Exception exc) {
                return "error:post-" + exc.Message;
            }
        }

Step 2: Create getpostdata.aspx to consume request

  protected void Page_Load(object sender, EventArgs e)
    {
        //To check incoming request method
        if (Request.HttpMethod.ToString() == "POST") {
            if (Request.Form["csr"] != null)
            {
                var  _csr = Request.Form["csr"]; //assign request value
                Response.Write("Posted CSR: " + _csr);
            }
        }
    }