5

我正在尝试将一些数据发布到我不拥有的 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;
}
4

1 回答 1

4

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

于 2012-12-21T18:43:45.577 回答