WCF服务不喜欢单引号

时间:2012-12-21 17:32:33

标签: c# wcf xml-serialization

我正在尝试将一些数据发布到我不拥有的WCF服务。我正在使用XmlSerializer来格式化消息,这会产生包含单引号的数据的问题。

拥有这样的节点

...
<FirstName>D'Arcy</FirstName>
...

导致服务抛出“400 bad request”异常。如果我像这样在Fiddler中手动构建请求

...
<FirstName>D&quot;Arcy</FirstName>
...

然后就可以了。

我很困惑为什么会这样做。各种在线XML验证器声称我的原始XML是有效的,但WCF不喜欢它?有什么方法可以解决/解决方法吗?


以下是我的代码:

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;
}

1 个答案:

答案 0 :(得分:3)

原来这个WCF服务通过使用直接查询(非参数化)将数据插入到他们的数据库中,并且不会转义单引号。这也非常令人困惑,因为对我而言,HTTP状态400意味着它是反序列化的问题或框架中的类似问题。
抱歉打扰所有人:(