【发布时间】:2015-07-01 13:40:40
【问题描述】:
我有一个使用未在服务定义中定义的对象的 WCF 服务(从代码开始)。因此,我必须使用 [XmlInclude] 属性来让 WCF 了解如何对其进行序列化。
出于某种原因,这不起作用,WCF 仍然抱怨(我使用跟踪发现了异常)我必须对已定义的类型使用 [XmlInclude]。
我在这里错过了什么?
启动 WCF 服务的代码
ServiceHost host = new ServiceHost(typeof(MyService), "http://localhost/myservice");
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy12;
host.Description.Behaviors.Add(smb);
host.Open();
服务实现
[WebService(Namespace = "http://services.mysite.com/MyService")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class MyService : WebService, IMyService {
[WebMethod]
[XmlInclude(typeof(InnerObject))]
public MyReturnObject Test() {
return new MyReturnObject(new InnerObject());
}
}
服务定义/接口
[ServiceContract]
public interface IMyService {
[OperationContract, XmlSerializerFormat(Style = OperationFormatStyle.Document)]
MyReturnObject Test();
}
返回类型
MyReturnObject 类包含一个通用对象,可以包含我想要的任何内容。在这个例子中,我包含了上面定义的 InnerObject 类型,类型定义如下所示。
[KnownType(typeof(InnerObject))]
public class MyReturnObject {
public object Content { get; set; }
public MyReturnObject(object content) {
Content = content;
}
}
public class InnerObject {
public int Foo;
public string Bar;
// And some other properties
}
完全异常
System.InvalidOperationException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
类型 InnerObject 不是预期的。使用 XmlInclude 或 SoapInclude 属性指定静态未知的类型。
【问题讨论】: