【问题标题】:WCF service throws "The type [...] was not expected. Use the XmlInclude [...]" even if XmlInclude is already being usedWCF 服务抛出“类型 [...] 不是预期的。使用 XmlInclude [...]”即使 XmlInclude 已被使用
【发布时间】: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 属性指定静态未知的类型。

【问题讨论】:

    标签: c# .net wcf


    【解决方案1】:

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

    【讨论】:

    • 在哪个班级?在MyReturnObjectIMyServiceMyService
    • 关于服务实现MyService
    • 将其添加到 MyService 无效。我尝试将它添加到IMyService,这有点工作,异常不再出现,但返回的数据不是正确的对象。我正在使用webservicestudio.codeplex.com 来测试服务。使用接口上的[ServiceKnownType],我将对象作为 XmlNodes 数组而不是正确的对象。如果我专门将MyReturnObject 更改为直接引用InnerObject,我会得到一个正确的对象,WebService Studio 会将其显示为一个正确的对象,而不仅仅是一个 XmlNodes 数组。
    • 由于某种未知原因,一切突然开始工作([ServiceKnownType])。我现在已经从返回类型中删除了[KnownType],从ServiceImplementation 中删除了[XmlInclude],一切正常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多