1

我正在使用提供以下调用和响应的第三方 Web 服务

http://api.athirdparty.com/rest/foo?apikey=1234

<response>
  <foo>this is a foo</foo>
</response>

http://api.athirdparty.com/rest/bar?apikey=1234

<response>
  <bar>this is a bar</bar>
</response>

这是我写的合约和支持类型

[ServiceContract]
[XmlSerializerFormat]
public interface IFooBarService
{
    [OperationContract]
    [WebGet(
        BodyStyle = WebMessageBodyStyle.Bare,
        ResponseFormat = WebMessageFormat.Xml,
        UriTemplate = "foo?key={apikey}")]
    FooResponse GetFoo(string apikey);

    [OperationContract]
    [WebGet(
        BodyStyle = WebMessageBodyStyle.Bare,
        ResponseFormat = WebMessageFormat.Xml,
        UriTemplate = "bar?key={apikey}")]
    BarResponse GetBar(string apikey);
}

[XmlRoot("response")]
public class FooResponse
{
    [XmlElement("foo")]
    public string Foo { get; set; }
}

[XmlRoot("response")]
public class BarResponse
{
    [XmlElement("bar")]
    public string Bar { get; set; }
}

然后我的客户看起来像这样

static void Main(string[] args)
{
    using (WebChannelFactory<IFooBarService> cf = new WebChannelFactory<IFooBarService>("thirdparty"))
    {
        var channel = cf.CreateChannel();
        FooResponse result = channel.GetFoo("1234");
    }
}

当我运行它时,我得到以下异常

无法使用 XmlSerializer 反序列化具有根名称“响应”和根命名空间“”的 XML 主体(用于操作“GetFoo”和合同(“IFooBarService”,“ http://tempuri.org/ ”))。确保将 XML 对应的类型添加到服务的已知类型集合中。

如果我从 中注释掉GetBar操作IFooBarService,它工作正常。我知道我在这里遗漏了一个重要的概念——只是不知道要寻找什么。构造我的合约类型以便正确反序列化它们的正确方法是什么?

4

2 回答 2

2

我会说您的第三方服务严重损坏。这里有一个命名空间冲突 - 有两个元素被命名response但具有不同的 XML 模式类型。

我认为您将不必使用任何涉及反序列化此 XML 的 .NET 技术。没有办法告诉 .NET 将 XML 反序列化为哪种 .NET 类型。

您只需要手动完成即可。LINQ to XML 可用于此目的。

于 2010-03-12T01:35:29.687 回答
0

您可以尝试使用这样的响应类:

[XmlRoot("response")]
public class Response
{
    [XmlElement("foo")]
    public string Foo { get; set; }

    [XmlElement("bar")]
    public string Bar { get; set; }
}
于 2011-11-09T13:57:58.967 回答