Click here to Skip to main content
15,888,113 members
Articles / Web Development / IIS
Article

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

Rate me:
Please Sign up or sign in to vote.
3.79/5 (31 votes)
18 May 2005CPOL 367K   61   23
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:

C#
 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:

C#
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)


Written By
Architect
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Member 1051082221-Mar-13 3:10
professionalMember 1051082221-Mar-13 3:10 
QuestionGreat, thank you Pin
Roger Taylor5-Nov-12 1:04
Roger Taylor5-Nov-12 1:04 
QuestionGreat, thanks Pin
Roger Taylor5-Nov-12 1:04
Roger Taylor5-Nov-12 1:04 
GeneralRedirect to the page Pin
hichamveo10-Feb-10 22:36
hichamveo10-Feb-10 22:36 
GeneralMy vote of 1 Pin
Reza Qorbani23-Jan-10 13:56
Reza Qorbani23-Jan-10 13:56 
GeneralRe: My vote of 1 Pin
Pinhead_Me10-Mar-11 14:31
Pinhead_Me10-Mar-11 14:31 
GeneralThanks Pin
theonlyremedy5-Nov-09 1:14
theonlyremedy5-Nov-09 1:14 
GeneralThanks Pin
redware.com2-Nov-09 0:09
redware.com2-Nov-09 0:09 
GeneralNice Pin
sashidhar8-Oct-09 19:49
sashidhar8-Oct-09 19:49 
GeneralCode please Pin
Fanie23-Sep-09 1:17
Fanie23-Sep-09 1:17 
GeneralRe: Code please Pin
S Sansanwal23-Sep-09 19:10
S Sansanwal23-Sep-09 19:10 
GeneralThanks for the code Pin
Sarif Bin Ishak28-Jul-09 22:11
Sarif Bin Ishak28-Jul-09 22:11 
Questionhow to post a string to an URL Pin
naveen_bij23-Dec-08 22:15
naveen_bij23-Dec-08 22:15 
QuestionHow to get the values from the database into a html page using C#.Net Pin
satyaanand.andra@gmail.com29-Jun-08 20:52
satyaanand.andra@gmail.com29-Jun-08 20:52 
AnswerRe: How to get the values from the database into a html page using C#.Net Pin
S Sansanwal30-Jun-08 0:44
S Sansanwal30-Jun-08 0:44 
GeneralRe: How to get the values from the database into a html page using C#.Net Pin
satyaanand.andra@gmail.com30-Jun-08 2:11
satyaanand.andra@gmail.com30-Jun-08 2:11 
QuestionTrouble with the server side code? Pin
Arulraja Livingston26-Jun-08 9:39
Arulraja Livingston26-Jun-08 9:39 
QuestionBy the way, this used to work under IIS 5, but now under 6 it doesn't anymore. Pin
epastorejr2-Nov-06 0:21
epastorejr2-Nov-06 0:21 
I've got this piece of code, originated from Alex Feinman, which is intended to upload XML files from Pocket PC to an IIS virtual directory. It used to run smoothly under IIS 5, but as soon as I put it to run under IIS 6 it refused to work. The log file tells me that :

2006-11-01 14:52:59 192.168.0.38 1224 192.168.0.11 80 HTTP/1.1 PUT /tr/0220061101122605000000001JR.xml 400 1 BadRequest DefaultAppPool
2006-11-01 14:53:43 192.168.0.38 1224 192.168.0.11 80 HTTP/1.1 PUT /tr/0220061101122605000000001JR.xml 400 1 Connection_Dropped DefaultAppPool
2006-11-01 14:58:41 192.168.0.38 1236 192.168.0.11 80 HTTP/0.0 Invalid - 400 - Verb -
2006-11-01 14:58:45 192.168.0.38 1237 192.168.0.11 80 HTTP/0.0 Invalid - 400 - Verb -
<repeats line="" above="" many,="" many="" times="">

and once :


2006-11-01 14:52:59 192.168.0.38 1224 192.168.0.11 80 HTTP/1.1 PUT /tr/0220061101122605000000001JR.xml 400 1 BadRequest DefaultAppPool
2006-11-01 14:53:43 192.168.0.38 1224 192.168.0.11 80 HTTP/1.1 PUT /tr/0220061101122605000000001JR.xml 400 1 Connection_Dropped DefaultAppPool
2006-11-01 14:58:41 192.168.0.38 1236 192.168.0.11 80 HTTP/0.0 Invalid - 400 - Verb -
2006-11-01 14:58:45 192.168.0.38 1237 192.168.0.11 80 HTTP/0.0 Invalid - 400 - Verb -
<repeats line="" above="" many,="" many="" times="">


Now, is there anything I can do to make it run under IIS 6 ? Dead | X|

Code follows. Thanks very much !

Jr



Public Function UploadIt(Optional ByVal logErrors As Boolean = False) As Integer
'Alex Feinman code next
Dim i, j As Integer
Dim data As String
Dim Url As String
Dim mstrFilename As String
Dim req As HttpWebRequest
Dim resp As HttpWebResponse ' = Nothing
Dim reqStream As Stream
Dim code As HttpStatusCode
Dim ascii As Encoding
Dim mblnFileRead As Boolean
Dim muriURI As Uri
Dim mblnFileSent As Boolean
Dim mblnURIOk As Boolean
If Me.Files.Count = 0 Or mstrWhereTo = "" Then Exit Function
j = Me.Files.Count - 1
Url = mstrWhereTo
If Right(Url, 1) <> "/" Then
Url = Url & "/"
End If
ascii = Encoding.ASCII
For i = 0 To j
Try
Dim rdr As New StreamReader(Me.Files.Item(i).FileNameAndPath)
data = rdr.ReadToEnd
rdr.Close()
rdr = Nothing
mblnFileRead = True
Catch ex As Exception
If logErrors Then
TextLogger.Log(ex.Message & " in HTTPUpload.UploadIt (data assignment)")
End If
mblnFileRead = False
End Try
If mblnFileRead Then
'Build the target url from the virtual directory and file name
mstrFilename = Path.GetFileName(Me.Files.Item(i).FileNameAndPath)
'If web server is running UrlScan it will reject .exe file as an unsafe extension
'If Path.GetExtension(mstrFilename) = ".exe" Then
'mstrFilename = Path.ChangeExtension(mstrFilename, "ex_")
'End If
'Make sure the url is properly escaped. Uri class takes care of that
Try
muriURI = New Uri(Url & mstrFilename)
req = WebRequest.Create(muriURI) 'HttpWebRequest.Create(muriURI)
muriURI = Nothing
mblnURIOk = True
Catch ufwe As UriFormatException
If logErrors Then
TextLogger.Log(ufwe.Message & " in HTTPUpload.UploadIt (URI and WebRequest instantiation)")
End If
mblnURIOk = False
Catch ex As Exception
If logErrors Then
TextLogger.Log(ex.Message & " in HTTPUpload.UploadIt (URI and WebRequest instantiation)")
End If
mblnURIOk = False
End Try
If mblnURIOk Then
'req.Pipelined = True
'req.KeepAlive = True
req.Method = "PUT"
req.AllowWriteStreamBuffering = True
req.ContentType = "text/xml"
req.Timeout = 1 * 30 * 1000 'half a minute timeout
'req = CType(WebRequest.Create(Url), HttpWebRequest)
'req = CType(WebRequest.Create(mstrWhereTo), HttpWebRequest)
If mstrUserName <> "" And mstrPassword <> "" Then
'req.AllowWriteStreamBuffering = True
req.Credentials = New NetworkCredential(mstrUserName, mstrPassword)
'Else
'req.Credentials = CredentialCache.DefaultCredentials
End If
'For large files (> 50KB) you may want to uncomment the next line
'req.SendChunked = true;
req.ContentLength = data.Length
Try
reqStream = req.GetRequestStream()
Dim maContents() As Byte = ascii.GetBytes(data)
reqStream.Write(maContents, 0, maContents.Length) 'data.Length)
reqStream.Flush()
reqStream.Close()
'reqStream = Nothing
maContents = Nothing
mblnFileSent = True
Me.Files.Item(i).Sent = True
Catch wex As WebException
If logErrors Then
TextLogger.Log(wex.Message & " in HTTPUpload.UploadIt (WebException in GetRequestStream)")
End If
mblnFileSent = False
Catch ufwe As UriFormatException
If logErrors Then
TextLogger.Log(ufwe.Message & " in HTTPUpload.UploadIt (UriFormatWebException in GetRequestStream)")
End If
mblnFileSent = False
Catch ex As Exception
If logErrors Then
TextLogger.Log(ex.Message & " in HTTPUpload.UploadIt (Exception in GetRequestStream)")
End If
mblnFileSent = False
'Me.Files.Item(i).Sent = False
End Try
'If mblnFileSent Then
Try
resp = req.GetResponse()
code = resp.StatusCode
If code.ToString = "OK" Or code.ToString = "Created" Then
Me.Files.Item(i).Sent = True
End If
Catch ex As Exception
If logErrors Then
TextLogger.Log(ex.Message & " in HTTPUpload.UploadIt (in GetResponse)")
End If
Finally
resp.Close()
End Try
'End If
End If
req = Nothing
End If
Next
reqStream = Nothing
ascii = Nothing
UploadIt = 1
'code = resp.StatusCode
End Function
GeneralWebRequest and WebResponse are in System.Net namespace Pin
glavonjahans_chrstn30-Sep-06 10:48
glavonjahans_chrstn30-Sep-06 10:48 
QuestionCould you post all of the code? Pin
platorres13-Sep-06 9:41
platorres13-Sep-06 9:41 
GeneralIt doesn't work for me Pin
marco311-Jun-06 4:41
marco311-Jun-06 4:41 
GeneralThis is a quick and easy guide!! Pin
ideasfreelance10-Nov-05 8:03
ideasfreelance10-Nov-05 8:03 
GeneralNo writeup Pin
vikramk1-Oct-05 13:24
vikramk1-Oct-05 13:24 

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

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