Post XML Data to an ASP.NET Page using C#

Original Post:

Code For Posting

To post XML, use the following function:

   WebRequest req = null;
   WebResponse rsp = null;
    string fileName = "C:\test.xml";
    string uri = "http://localhost/PostXml/Default.aspx";
    req = WebRequest.Create(uri);
    //req.Proxy = WebProxy.GetDefaultProxy(); // Enable if using proxy
    req.Method = "POST";        // Post method
    req.ContentType = "text/xml";     // content type
    // Wrap the request stream with a text-based writer
    StreamWriter writer = new StreamWriter(req.GetRequestStream());
    // Write the XML text into the stream
    // Send the data to the webserver
    rsp = req.GetResponse();
   catch(WebException webEx)
   catch(Exception ex)
    if(req != null) req.GetRequestStream().Close();
    if(rsp != null) rsp.GetResponseStream().Close();
   }Function to read xml data from local system
  /// <span class="code-SummaryComment"><summary></span>
  /// Read XML data from file
  /// <span class="code-SummaryComment"></summary></span>
  /// <span class="code-SummaryComment"><param name="file"></param>
  /// <span class="code-SummaryComment"><returns>
returns file content in XML string format</returns></span>
  private string GetTextFromXMLFile(string file)
   StreamReader reader = new StreamReader(file);
   string ret = reader.ReadToEnd();
   return ret;

Code For Reading Posted Data

Now, on the Web server in the ASP.NET page, write the following code to access the posted data:

private void Page_Load(object sender, EventArgs e)
     page.Response.ContentType = "text/xml";
    // Read XML posted via HTTP
    StreamReader reader = new StreamReader(page.Request.InputStream);
    String xmlData = reader.ReadToEnd(); 

Leave a Reply

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

You are commenting using your 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 )


Connecting to %s