Click here to Skip to main content
Click here to Skip to main content

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

, 18 May 2005 CPOL
Rate this:
Please Sign up or sign in to vote.
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
  /// <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>
  /// <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();
   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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

S Sansanwal
Architect
Australia Australia
No Biography provided

Comments and Discussions

 
GeneralCode please PinmemberFanie23-Sep-09 1:17 
GeneralRe: Code please PinmemberS Sansanwal23-Sep-09 19:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.141022.2 | Last Updated 18 May 2005
Article Copyright 2005 by S Sansanwal
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid