在WCF服务中序列化MethodBase和Exception类型

Caf*_*eek 1 .net service wcf datacontractserializer

我创建了一个用于记录异常的WCF服务(我意识到如果网络出现故障,就不会记录任何内容......有回退的地方)

无论如何,它有两种方法

int LogException(MethodBase methodBase, Exception exception)
int LogMessage(MethodBase methodBase, string message, string data)
Run Code Online (Sandbox Code Playgroud)

当我尝试将服务添加到新项目时,不会创建.cs文件.我运行了svcutil,并将.cs和config设置复制到项目中,并尝试使用生成的客户端调用服务.我收到以下两个错误

尝试序列化参数http://tempuri.org/:methodBase时出错 .InnerException消息是'Type'System.Reflection.RuntimeMethodInfo',数据协定名称为'RuntimeMethodInfo:http://schemas.datacontract.org/2004/07/System.Reflection'不是预期的.考虑使用DataContractResolver或将任何静态未知的类型添加到已知类型列表中 - 例如,通过使用KnownTypeAttribute属性或将它们添加到传递给DataContractSerializer的已知类型列表中.有关更多详细信息,请参阅InnerException.

内心异常

键入'System.Reflection.RuntimeMethodInfo',数据协定名称为'RuntimeMethodInfo:http://schemas.datacontract.org/2004/07/System.Reflection'.考虑使用DataContractResolver或将任何静态未知的类型添加到已知类型列表中 - 例如,通过使用KnownTypeAttribute属性或将它们添加到传递给DataContractSerializer的已知类型列表中.

我需要做些什么来完成这项工作?

McK*_*Kay 5

通过WCF进行通信时,WCF需要准确了解将跨边界发送的内容.所以采用"异常"是好的,但几乎总是,你将传递异常的子类型,所以你需要告诉合约哪些类型的异常将通过边界传递.MethodBase也是如此.你可能想告诉它你实际上会在某些时候传递一个MethodInfo.

因为这些不是您的类型,您可能无法使用KnownType属性(该属性通常放在基类或接口上).在这种情况下,您需要使用数据合同解析器.它告诉序列化/反序列化引擎如何查找子类型.

http://msdn.microsoft.com/en-us/library/ee358759.aspx

虽然您可以使用ServiceKnownType属性.你的合同应该是这样的:

[DataContract]
public interface ILoggingStuff // choose a better name than this
{
    [OperationContract]
    [ServiceKnownType(typeof(MethodInfo))]
    int LogException(MethodBase methodBase, Exception exception);
    [OperationContract]
    [ServiceKnownType(typeof(MethodInfo))]
    int LogMessage(MethodBase methodBase, string message, string data);
}
Run Code Online (Sandbox Code Playgroud)

这告诉WCF,MethodBase可以使用降序类型MethodInfo.