簡體   English   中英

WCF服務引發“未預期類型[…]。 即使已經使用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();
}

退貨類型

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,版本= 4.0.0.0,文化=中性,PublicKeyToken = b77a5c561934e089

不應使用InnerObject類型。 使用XmlInclude或SoapInclude屬性可以指定靜態未知的類型。

您應該在wcf服務上使用[ServiceKnownType]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM