无法将对象发送到SOAP Web Service

时间:2012-03-20 08:21:36

标签: c# web-services soap xml-serialization

我有一个方法肥皂网服务:

string startReaction(object reaction);

在该方法中,我将此对象转换为它的真实类型:

Reaction reactionObj = (Reaction)reaction;
...

我在表单项目中有相同的Reaction类(窗口用于调用此ws)。在这里,我创建Reaction对象实例并用数据填充它并尝试发送到Web服务。

string data = webserviceReference1.startReaction(reaction);

我也尝试过:

string data = webserviceReference1.startReaction(reaction as object);

但没有。 然后我尝试在Reaction类上添加这个属性:

[XmlInclude(typeof(object))]
public class Reaction{...

但没有。 我得到的错误是:

There was an error generating the XML document. :: System.InvalidOperationException: The type Demo.Form1+Reaction was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.

1 个答案:

答案 0 :(得分:4)

您必须在sevrice的元数据中公开Reaction类,以便客户了解它:

[WebMethod]
[XmlInclude(typeof(Reaction))]
[XmlInclude(typeof(Foo))]
[XmlInclude(typeof(Bar))]
// ... the list goes on with all possible types that you might want to pass to this method
// since you used object as argument you need to explicitly say which types are allowed here
public string startReaction(object reaction)
{
    ...
}

您不应该在客户端上重新定义同一个类,因为这不起作用。服务器不知道如何序列化它。正确的方法是让Web服务公开WSDL中的所有已知类型,这样当您在客户端上生成强类型代理时,将导入所有这些类型,并且您将能够调用该服务。