Link to home
Start Free TrialLog in
Avatar of Rajkumar Gs
Rajkumar GsFlag for India

asked on

C# code to send an XML to a webservice

I have attached the C# code that I have tried, but it is returning an error message. (In this code, I am reading the XML file contents and sent it to the web service.)
"The remote server returned an error: (500) Internal Server Error."

I have tried the same XML in the tool soapUI 3.5 ( ). This tool is showing the response from webservice.
I am trying to the do the same thing in C# code and display the response code in web page using ASP.Net / C#

What am I doing wrong... ?

using System;
using System.Configuration;
using System.Data;
using System.Net;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Xml;
using System.IO;
using System.Text;

public partial class _Default : System.Web.UI.Page 
    protected void Page_Load(object sender, EventArgs e)

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(HttpContext.Current.Server.MapPath(".") + "\\createEmployee.XML");
        StringBuilder rawXml = new StringBuilder();

        PostXml("", rawXml.ToString());

    public void PostXml(string url, string xml)
        byte[] bytes = Encoding.UTF8.GetBytes(xml);
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";
        request.ContentLength = bytes.Length;
        request.ContentType = "text/xml";
        using (Stream requestStream = request.GetRequestStream())
            requestStream.Write(bytes, 0, bytes.Length);

	// <-- Error :- The remote server returned an error: (500) Internal Server Error." (Attached the code)
        HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
        if (response.StatusCode != HttpStatusCode.OK)
            string message = String.Format("POST failed. Received HTTP {0}",
            throw new ApplicationException(message);

    static string GetXmlString(XmlDocument xmlDoc)

        // Now create StringWriter object to get data from xml document.
        StringWriter sw = new StringWriter();
        XmlTextWriter xw = new XmlTextWriter(sw);
        return sw.ToString();


Open in new window

Avatar of dschauhan82

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dschauhan82

//the URL is on the application
string strURL = this.txtURL.Text;
//go find the raw XML
this.openFileDialog1.Filter = "XML files (*.xml) | *.xml";

//load the XML
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(this.openFileDialog1.FileName.ToString ());
//Create the Web request
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(strURL);

//set the properties
request.Method = "POST";
request.ContentType = "text/xml" ;
request.Timeout = 30 * 1000;
//open the pipe?
Stream request_stream = request.GetRequestStream();
//write the XML to the open pipe (e.g. stream)
//CLOSE THE PIPE !!! Very important or next step will time out!!!!

//get the response from the webservice
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
Stream r_stream = response.GetResponseStream();
//convert it
StreamReader response_stream = new
StreamReader(r_stream,System.Text.Encoding.GetEnco ding("utf-8"));
string sOutput =response_stream.ReadToEnd();

//display it
this.txtAbstract.Text = sOutput;

//clean up!

Avatar of Rajkumar Gs


Thanks dschauhan82 for your help!

I have tried this code and getting the same error messsage - "The remote server returned an error: (500) Internal Server Error."

As I mentioned in question, the tool soapUI tool displays the exact error message.
Can you please tell why the exact error response message is not displaying in your code & mine...!?

Thanks again
I used soapUI tool ( ) to send XML to a webservice. This tool shows the repsonse from Webservice.

But when I tried the code ( http:#33594986 ), it is showing another error instead of showing the response from Webservice.

(Please open the attached screenshot)

What's I am doing wrong here ?

How can I send XML to a Webservice and receive the response from Webservice in Asp.Net application using C# code ?

have you 'escaped' all special characters like "<" and ">" ? you should replace them by ">" etc.
oops, the last ">" should read "semicolon & gt" - replace words by appropriate character and remove spaces
Thanks for your comment, alexey.

I have n't anything regarding handling special characters. - actually i was not aware about that.
Could you please post the C# code regarding the same ?

it is just as simple as the following snippet. I'm not 100% sure it resolves your problems, but it's worth a try

str = str.Replace(">","&gt;").Replace("<","&lt;");

Open in new window

Attached one was the code I used to post XML to web service.

I modified these lines

        // XML File
        XmlDocument xmlDoc = new XmlDocument();
        byte[] postBytes = encoding.GetBytes(xmlDoc.InnerXml.ToString());


        // XML File
        XmlDocument xmlDoc = new XmlDocument();
        string XMLFileContents = "";
        XMLFileContents = xmlDoc.InnerXml.ToString();
        XMLFileContents = XMLFileContents.Replace(">", ">").Replace("<", "<");
        byte[] postBytes = encoding.GetBytes(XMLFileContents);

and tried as per your suggestion. Still getting the same error message.

public string PostXMLtoWebService(string sourceXMLFile)
        // Webservice
        HttpWebRequest hwrRequest = (HttpWebRequest)HttpWebRequest.Create("");
        hwrRequest.Method = "POST";
        hwrRequest.ContentType = "text/xml";
        UTF8Encoding encoding = new UTF8Encoding();

        // XML File
        XmlDocument xmlDoc = new XmlDocument();
        byte[] postBytes = encoding.GetBytes(xmlDoc.InnerXml.ToString());

        hwrRequest.ContentLength = postBytes.Length;

        Stream postStream = hwrRequest.GetRequestStream();
        postStream.Write(postBytes, 0, postBytes.Length);

        HttpWebResponse hwrResponse = (HttpWebResponse)hwrRequest.GetResponse();
        Stream responseStream = hwrResponse.GetResponseStream();
        XmlTextReader xtrSmp = new XmlTextReader(responseStream);

        string strXm = xtrSmp.ReadInnerXml();

        return strXm;

Open in new window

If I am right, If there is anything wrong with the input XML to Webservice, we should get the proper error response from webservice in XML format. (See attached error response I got from webservice, when passed invalid values in XML file using soapUI tool)

But in this case, some other crash seems to be happening.

Is the code is right intended to post XML to a webservice ? Any alternative method using C# code ?

<soapenv:Envelope xmlns:soapenv="" xmlns:xsd="" xmlns:xsi="">
         <faultstring>| UPDATEENTITY: NO ENTITY FOUND FOR EXTERNAL_ENTITY_ID = 222</faultstring>

Open in new window

ok, what I don't understand - in the string after Replace().Replace() - do you have any special xml characters?
(see   for details)

what happens when you send some arbitrary string instead of xml?
I have attached the XML file that I used.
I have renamed some relevant portions (text only), which is private to our company

hmm, I don't think it is anything to do with xml. I've tried sending plain text with the same exact result.

can you debug it at web service side? what language was it developed in? from the url in your code it doesn't seem to be a webservice at all :)

in general, you'd like to add a web reference or service reference (depending on the VS version), so then VS builds a wrapper for you and does all 'black jobs' for you in terms of serializing objects
When I passed a string 'test' instead of XML - same error message :(

so what about debugging the web service (or whatever it is)? you should be able to put a breakpoint and see what happens.

right now it looks like you have some virtual folder on your webserver, and when one access it the default script is executed and writes back to http response stream :)
Webservice is not ours. It is the webservice provided by client. So no scope with debugging webservice :)


I tried it in a different way. Instead of posting XML with the code I posted before, tried to use their class. (See attachment)

Only this object is available in their webservice class now, where we need to pass I think XML.
( message.process(object process1)  )

When I tried this way

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(sourceXMLFile); message = new;

Error is - " Unknown 'process' element found in body of SOAP message"

When I tried like
Error message is
"There was an error generating the XML document."

Any idea ?
Sorry. missed the attachment.

ahh, that's what I was looking for ;) - so it is java ws, and it does give you a wrapper class.

try simple text string as a parameter - and you need to read their docs to see what's expected in MessageServiceService.process() method

In general, if you're fancy connecting to web service over raw HTTP then you MUST build all SOAP enveloping stuff manually, it's not just HTTP POST :)

But I'm sure you have the wrapper (MessageServiceService class) and can use it with proper parameter
Yes. I think we are more close to the right way :)

I will ask client what type of parameter, we need to pass. Now simply, it is 'object process1' - which is confusing. I tried those ways that I mentioned in previous comment - http:#33625435

We asked client about the error regarding sending XML over HTTP POST. We are having a VBScript file that was sent by them previously, which they successfully tested over their webservice.

Regarding our query, client replied with a doubt that we may have missed this setting
objXmlHTTP.setRequestHeader "SOAPAction:" , serviceUrl
in our C# code. (Please see the attached vbs file)

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
excellent :) , so all encoding/decoding is done in XMLHTTP

The link you provided in your first comment - http:#33594977 - have the right code which in javascript, which need converting to C#. But I was behind your second comment - http:#33594986 - as it is C#, I thought it will work with some modification.

Thanks for your help

Hi Alexey &  dschauhan82,
Thanks you guys for your help.

I think it is better to accept my comment as the 'Accepted Solution' (0 points) and yours as 'Assisted Solution', only because for any one who search in future in EE for similar issue - "How to send an XML to a Webservice in C#' - would first get into the comment having right code and description.

As you both provided me the same solution, I think it is justice to split points to you both.

no objections from my side :)
Thanks alexey. Hope dschauhan82 also :) But I cannot close this question - Error message "Each point split must be at least 20 points" Points I assigned for each split is much far above 20 points!    Requesting Admin Attention...    Raj
I guess you should assign points to your own answer too
For my comments, there is no option to assign points. For other expert's comments only have option to select and assign points.

Normally asker's solution will be assigned 0 points.

Hi, I've got a question for RajkumarGS or anybody that can help me.

I'm handling a similar scenario (using Visual C# 2010): I should send an XML file to a WebService.
The solution in the post  33634709 seems to be really close to my needs.
I just need to understand how to refer to a specific method of the Web Service, to which send the XML file.

To define the Service URL in the code above, RajkumarGS wrote:
string serviceUrl = "";

Open in new window

In my case, the Web Service URL includes the .asmx extension; then something like:

There're two different methods that could be called to pass the XML file (eg. MethodName1 and MethodName2).
I tried to edit the ServiceUrl with something like:
string serviceUrl = "";

Open in new window

but I got a fault error:
  <faultstring>System.Web.Services.Protocols.SoapException: Server did not recognize the value of HTTP Header SOAPAction: ... </faultstring>

So, the question is: how do I adapt the RajkumarGS code (if possible) to achieve this, or how it is supposed to be done. I'm quite new to Web Service etc, so I'm looking for an easy way to perform it.
Any code examples are really welcome and would be appreciated.
Remember, I'm using the Visual C# environment (but if you got any easier way, like stand-alone scripts, please don't hesitate to post it!)