Reputation: 7105
I have a WCF RESTful service that is supposed to return a name and surname of a customer as a XML response, the service is defined as indicated below
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Xml,
ResponseFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "/GetNameAndSurname")]
string GetNameAndSurname();
The problem I'm experiencing is that the XML response that is returned was not in normal XML as expected, for example
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
<Customer;
<Name>Andre</Name>
<SurnameName>Lombaard</SurnameName>
>
</string>
I'm not sure if it is the service returning the response this way or if it is the way I'm reading the data, just for informational purposes I included the code I use to read the response below,
var request = HttpWebRequest.Create(url);
request.Method = "POST";
request.Timeout = 2 * 60 * 1000;
byte[] byteArray = Encoding.UTF8.GetBytes(xml);
request.ContentType = "text/xml";
request.ContentLength = byteArray.Length;
var dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
var response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream, Encoding.UTF8);
dataStream.Flush();
var results = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
How do I get normal XML without having to perform various replacements on the characters received in the response.
At the moment I replace the characters with the code below. This is not ideal
results = results.Replace("</string>", String.Empty);
results = results.Replace("<", "<");
results = results.Replace(">
", ">");
results = results.Replace(">", ">");
results = Regex.Replace(results, "<string .*?\\>", String.Empty);
Upvotes: 3
Views: 1779
Reputation: 40383
The service is doing exactly what it says it's doing - it's returning an XML-serialized string. I'm guessing the service code does some serialization of the Customer
object into a string before returning that. If you want the return type to be the Customer
, have the service method return a Customer
object instead of a string, and you should be good. It will be smart enough to serialize your Customer
into the appropriate XML string.
For testing your data out, you can use something like Fiddler to watch the raw HTTP request and response, so you can be sure exactly what's being requested and responded - but my guess is that it is coming back exactly as you're showing.
Definitely don't do that last thing with the string replaces. If you ever do need to do this, then look into XML decoding, possibly with one of the solutions found here.
Upvotes: 6