我正在使用提供以下调用和响应的第三方 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
,它工作正常。我知道我在这里遗漏了一个重要的概念——只是不知道要寻找什么。构造我的合约类型以便正确反序列化它们的正确方法是什么?