WCF 服务抛出 "The type [...] was not expected. Use the XmlInclude [...]" 即使 XmlInclude 已经被使用

WCF service throws "The type [...] was not expected. Use the XmlInclude [...]" even if XmlInclude is already being used

我有一个 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();
}

Return 类型

MyReturnObject class 包含一个通用对象,可以包含我想要的任何内容。对于这个例子,我包含了一个上面定义的 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

The type InnerObject was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.

您应该在您的 wcf 服务上使用 [ServiceKnownType]