【问题标题】:WCF -Rest- DataContract : Deserialize XML wrapped responseWCF -Rest- DataContract:反序列化 XML 包装的响应
【发布时间】:2017-06-10 14:02:05
【问题描述】:

假设我们正在使用返回 xml 的 REST WCF 服务。

是否可以“自动”反序列化对 DataContract 的 xml 包装响应?

简单示例

类:

[DataContract]
public class TestClass
{
    [DataMember]
    string StringValue { get; set; }
    [DataMember]
    int IntValue { get; set; }
}

服务:

[OperationContract]
[WebGet(UriTemplate = "Test",
   BodyStyle      = WebMessageBodyStyle.Wrapped,
   RequestFormat  = WebMessageFormat.Xml,
   ResponseFormat = WebMessageFormat.Xml)]
TestClass Test();

客户:

using (WebClient webClient = new WebClient())
{
    webClient.Headers["Content-type"] = "application/xml";
    webClient.Encoding = Encoding.UTF8;
    return webClient.DownloadString($"{BASE_URL}/Test");
}

反序列化:

// With T as TestClass in or example.
public static T Deserialize<T>(string xml)
{
    using (Stream stream = new MemoryStream())
    {
        byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);
        stream.Write(data, 0, data.Length);
        stream.Position = 0;
        DataContractSerializer deserializer =
             new DataContractSerializer(typeof(T));
        return (T)deserializer.ReadObject(stream);
    }
}

此代码适用于裸响应。

由于 webClient 只返回完整的请求,输出 xml 包含三个包装器元素,并且 DataContractSerializer 尝试解析一个简单的字符串,现在不要来自 WCF 包装的响应(并且应该“忘记”包装器)。

目标是构建一个包装样式(裸/包装)无关紧要的客户端。

【问题讨论】:

    标签: c# xml rest wcf deserialization


    【解决方案1】:

    为什么不将输出反序列化为简单的 XML?像这样:

    public static T XmlDeserializer<T>(string xmlString)
    {
            var instance = default(T);
            var xmlSerializer = new XmlSerializer(typeof(T));
            using (var stringreader = new StringReader(xmlString))
                instance = (T)xmlSerializer.Deserialize(stringreader);
    
            return instance;
    }
    

    注意:由于默认的 xmlns 标签,您应该在客户端类中使用命名空间,如下所示:

    [DataContract(Namespace = "http://schemas.datacontract.org/2004/07/WcfWebService")]
    

    【讨论】:

    • 抱歉,但我的主要目标是同样的问题:处理包装和裸露的响应。
    • 亲爱的@Manea。请发布整个回复,以便我可以帮助您。谢谢。
    • 请查看我的示例中的 service:当它设置为 BodyStyle = WebMessageBodyStyle.Wrapped 时,返回的 xml 被“包装”,因此反序列化不起作用。我正在寻找一种反序列化 WCF 生成的 Xml 的方法,该方法应该适用于 WebMessageBodyStyle.Wrapped AND WebMessageBodyStyle.Bare。
    • 亲爱的@Manea。问题不在于序列化方法。它与您的输出类有关。当您更改 BodyStyle.Wrapped 您的输出更改。我不知道你是如何使用网络服务的,但如果你能捕获输出,你就会明白问题所在。
    猜你喜欢
    • 2012-06-23
    • 1970-01-01
    • 2012-09-01
    • 2011-06-28
    • 2014-08-31
    • 1970-01-01
    • 1970-01-01
    • 2015-03-29
    • 2022-06-17
    相关资源
    最近更新 更多