Search code examples
xmlhttprequestwebrequestwebresponse

Responding to a WebRequest


I have created a simple XML Request on test.aspx page.

System.Net.WebRequest req = System.Net.WebRequest.Create("http://server.loc/rq.aspx");

            req.ContentType = "text/xml";
            req.Method = "POST";

            string strData = "<root><test>test1 </test></root>";
            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(strData);
            req.ContentLength = bytes.Length;
            Stream os = req.GetRequestStream();
            os.Write(bytes, 0, bytes.Length);


            System.Net.WebResponse resp = req.GetResponse();
            if (resp == null) return;
            System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());

            string responsecontent = sr.ReadToEnd().Trim();

Now, on rq.aspx I want to anticipate webrequest and generate some kind of response based on strData. I really don't know how to access strData from web-request.


Solution

  • This is probably what you are looking for

    private void Page_Load(object sender, EventArgs e)
    {
        // Read XML posted via HTTP
        using (var reader = new StreamReader(Request.InputStream))
        {
            string xmlData = reader.ReadToEnd();
            // do something with the XML
        }
    }
    

    From this answer