I am trying to post some data to a WCF service I don't own. I am using XmlSerializer to format the message, which creates issues with data containing single quotes.
Having a node like this
...
<FirstName>D'Arcy</FirstName>
...
Causes service to throw "400 bad request" exception. If I manually construct request in Fiddler like this
...
<FirstName>D"Arcy</FirstName>
...
then it works just fine.
I am confused as to why would this be needed. Various online XML validators claim my original XML is valid, but WCF doesn't like it? Any way to fix/workaround?
Here is my code just in case:
static XmlSerializer RequestSerializer = new XmlSerializer(typeof(Message));
static XmlSerializer ResponseSerializer = new XmlSerializer(typeof(int), new XmlRootAttribute("int") { Namespace = "http://schemas.microsoft.com/2003/10/Serialization/" });
static XmlWriterSettings WriterSettings = new XmlWriterSettings { OmitXmlDeclaration = true, CloseOutput = false, Encoding = new UTF8Encoding(false) };
private static int PostData(Message msg)
{
var request = (HttpWebRequest)WebRequest.Create("https://...");
request.ContentType = "text/xml;charset=UTF-8";
request.Method = "POST";
using (var writer = XmlWriter.Create(request.GetRequestStream(), WriterSettings))
RequestSerializer.Serialize(writer, msg);
using (var response = (HttpWebResponse)request.GetResponse())
using (var responseStream = response.GetResponseStream())
{
return (int)ResponseSerializer.Deserialize(responseStream);
}
}
[XmlRoot("Order", Namespace = "http://...")]
public class Message
{
public string City;
public string Coupon;
public DateTime CreateDate;
public string Email;
public string FirstName;
public string Language;
public string LastName;
public int OrderID;
public string PostalCode;
public string ProductID;
public string Province;
public string StreetAddress1;
public string StreetAddress2;
}
Turns out this WCF service is inserting data into their DB by using straight up query (non-parametrized) and doesn't escape single quotes. It was really confusing too, since HTTP status 400 to me implies it was an issue with deserialization or something similar in the framework.
Sorry to bother everyone :(
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With