WCF 中 MessageContract 的已知类型

KnownType for MessageContract in WCF

我在我的 wcf 合同中使用 Stream 对象,因此被迫使用 MessageContract 而不是 DataContract

 [MessageContract]
    public class Document 
    {
        [MessageBodyMember(Order = 1)]
        public System.IO.Stream FileData;

}

 [MessageContract]
    public class A : Document 
    {
        [MessageBodyMember]
        public string input;

}

 [MessageContract]
    public class B : Document 
    {
        [MessageBodyMember]
        public string someProp;

}

[ServiceContract]
    public interface ISomeService
    {

        [OperationContract]
        Document SomeMethod(Document file);
}

我希望此服务的使用者创建 A 或 B 的对象并使用它调用服务。在服务方面,我可以将其类型转换为适当的对象,然后执行一些操作。

问题是我不能用 MessageContract 指定 KnownType 并且继承的合同在服务中使用或用 KnownType 声明之前不能暴露给客户。

我试过 google 但找不到与 KnownTypeMessageContract 相关的任何内容。

如评论中所建议...我用 KnownType 更新了我的消息合同,但它们仍然没有通过服务引用暴露给客户...

[MessageContract]
    [KnownType(typeof(FileSystemStoredDocument))]
    [KnownType(typeof(FileBoundStoredDocument))]
    [KnownType(typeof(SharepointStoredDocument))]

    public class Document : DocumentInfo, IDisposable
    {
}

谁能帮我看看这是怎么回事?

注意:所有KnownType都是继承自Document

消息合同描述了消息的确切外观。它们确实支持继承,但您必须指定您在特定操作中使用的确切消息协定。

如果您检查邮件的 body 部分:

ContractDescription.GetContract(typeof(ISomeService)).Operations[0].Messages[0].Body.Parts

您只会看到一部分 - Stream object。这与数据契约形成对比,其中 body 包含类型 Object 的一部分。所以你明白为什么 KnownType 在这里不起作用 .

ContractDescription class 用于生成 WSDL。请参阅 WsdlExporter class。)

可以做的是创建将包含在消息协定中的数据协定层次结构,例如

[MessageContract]
public class Document 
{
    [MessageHeader]
    public DocumentProperties Properties;

    [MessageBodyMember(Order = 1)]
    public System.IO.Stream FileData;
}

[DataContract]
[KnownType(typeof(A))]
[KnownType(typeof(B))]
public abstract class DocumentProperties { }

[DataContract]
public class A : DocumentProperties 
{
    [DataMember]
    public string input;
}

[DataContract]
public class B : DocumentProperties 
{
    [DataMember]
    public string someProp;
}

请注意,如果要传递 Stream,则不能有超过一个 body 成员,因此其余属性必须在 headers.[=18 中=]