c# - 数据契约已知类型和一组相互继承的接口(interface)

标签 c# wcf exception-handling datacontractserializer known-types

我开发(重写到 WCF)一个接受 string[] 并返回 ISection[] 的文件解析 Web 服务,但实际上这是一组嵌套接口(interface):

namespace Project.Contracts // Project.Contracts.dll
{
    public interface ISection { }

    public interface ISummarySection : ISection { }

    public interface IDataSection : ISection { }
}

和类:

namespace Project.Format.A // Project.Format.A.dll
{
    [DataContract]
    public class SummarySectionFormatA : ISummarySection { }

    [DataContract]
    public class DataSectionFormatA : IDataSection { }
}

服务接口(interface)及其实现:

[ServiceContract]
public interface IService // Project.Contracts.dll
{
    ISection[] Parse(string format, string[] data);
} 

[ServiceKnownType(typeof(SummarySectionFormatA))] // tried this also
[ServiceKnownType(typeof(DataSectionFormatA))]
public class Service : IService // Project.Service.dll
{
    public ISection[] Parse(string format, string[] data)
    {
        return Factory.Create(format).Parse(data);
    }
}

我尝试在服务器和客户端上配置 declaredTypes:

<system.runtime.serialization>
  <dataContractSerializer>
    <declaredTypes>
      <add type="Project.Contracts.ISumarySection, Project.Contracts">
        <knownType type="Project.Format.A.SummarySectionFormatA, Project.Format.A" />
      </add>
      <add type="Project.Contracts.IDataSection, Project.Contracts">
        <knownType type="Project.Format.A.DataSectionFormatA, Project.Format.A" />
      </add>
    </declaredTypes>
  </dataContractSerializer>
</system.runtime.serialization>

但还是报同样的错误:

"Type 'DataSectionFormatA' with data contract name 'DataSection:http://schemas.example.com/Parse' is not expected.

The underlying connection was closed: The connection was closed unexpectedly.

我无法使用 KnownTypeAttribute 修饰接口(interface),因为 Contracts 项目不引用 Format 项目,引用会破坏设计。这就是我要使用配置的原因。

最佳答案

看看下面的代码

[ServiceContract]
[ServiceKnownType(typeof(SummarySectionFormatA))]
[ServiceKnownType(typeof(DataSectionFormatA))]
public interface IService {}

public class Service : IService {}

关于c# - 数据契约已知类型和一组相互继承的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11272672/

相关文章:

python - 在解析器中报告非 fatal error 的 Pythonic 方法是什么?

c# - Unity Assets 包服务器自动化

c# - 如果不为空则从属性中获取值,否则使用 Linq 获取其他属性

c# - 是什么原因导致 svcutil 在代理远程服务器时建议使用 netNamedPipeBinding?

wcf - 在Azure上部署WCF服务: Web Role or Worker Role?

c# - 关闭 WPF GUI 应用程序的正确方法 : GetCurrentProcess(). Kill()、Environment.Exit(0) 或 this.Shutdown()

c# - 在 MVP WinForms 应用程序中验证

c# - 在 C# 中替换字符串

wcf - 将流保存到文件

c# - .Net Windows 服务向用户报告错误的最佳方式