WCF合同 - 名称空间和序列化exceptions
-
19-09-2019 - |
题
我正在使用第三方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");
}
}
当我运行这个时,我会得到以下异常
无法用root名称“响应”和root namespace''(用于操作'getfoo'和Contract(“ ifoobarService','','http://tempuri.org/'))使用XMLSerializer。确保将与XML相对应的类型添加到已知类型的服务集合中。
如果我评论 GetBar
操作来自 IFooBarService
, ,正常工作。我知道我在这里错过了一个重要的概念 - 只是不知道该寻找什么。构建我的合同类型的正确方法是什么,以便可以正确化它们?
解决方案
我会说您的第三方服务严重破坏了。这里有一个名称空间碰撞 - 有两个元素命名 response
但是具有不同的XML模式类型。
我认为您将不必使用任何涉及该XML的.NET技术。无法分辨.net在哪种.NET类型中进行XML的序列化。
您只需要手工做。 linq到XML为此目的方便。
其他提示
您可以尝试这样的响应类:
[XmlRoot("response")]
public class Response
{
[XmlElement("foo")]
public string Foo { get; set; }
[XmlElement("bar")]
public string Bar { get; set; }
}
不隶属于 StackOverflow