Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

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

0.00/5 (No votes)
18 May 2005 1  
This article describes the function to post XML data to an ASP.NET page and then read the data on an ASP.NET page

Code For Posting

To post XML, use the following function:

   WebRequest req = null;
   WebResponse rsp = null;
   try
   {
    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
    writer.WriteLine(this.GetTextFromXMLFile(fileName));
    writer.Close();
    // Send the data to the webserver
    rsp = req.GetResponse();
    
   }
   catch(WebException webEx)
   {
    
   }
   catch(Exception ex)
   {
    
   }
   finally
   {
    if(req != null) req.GetRequestStream().Close();
    if(rsp != null) rsp.GetResponseStream().Close();
   }Function to read xml data from local system
  /// <summary>
  /// Read XML data from file
  /// </summary>
  /// <param name="file"></param>
  /// <returns>returns file content in XML string format</returns>
  private string GetTextFromXMLFile(string file)
  {
   StreamReader reader = new StreamReader(file);
   string ret = reader.ReadToEnd();
   reader.Close();
   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(); 
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here