我试图通过 WCF 传递一个带有 Dictionary 属性的类,对于一种方法失败,但对于另一种方法有效。当类在 a 内返回时List
, 有用。但是当类在 a 中返回时DataTable
,客户端只是说连接已断开并且没有显示错误。
这是引起问题的类:
[DataContract]
public class DetailLog
{
[DataMember]
public string Name
{
get;
set;
}
[DataMember]
public string SubAction
{
get;
set;
}
[DataMember]
public Dictionary<string, string> Fields
{
get;
set;
}
[DataMember]
public string UserName
{
get;
set;
}
}
我开始创建一个没有问题的方法:
public List<DetailLog> GetDetailLog(List<int> IDs, List<int> actionTypeIds, List<int> userIds, DateTime beginDate, DateTime endDate)
然后我们需要创建一些非常动态的报告,因此我使用了我们之前用于其他动态报告的数据表。
但我需要传递 DetailLog 类,因此我创建了该类型的 DataTable 列:
public DataTable GetCustomDetailReport(int CustomReportID, List<CustomReportFilter> reportFilters)
{
DataTable data = new DataTable();
...
data.Columns.Add("DetailLog", typeof(DetailLog));
...
}
此方法在 WCF 主机端可以正常退出,但在客户端会出现连接丢失的错误。我尝试在界面中为OperationContract添加ServiceKnownType,但没有修复它:
[OperationContract]
[ServiceKnownType(typeof(DetailLog))]
DataTable GetCustomUserAuditReport(int CustomReportID, List<CustomReportFilter> reportFilters);
当该方法返回 DataTable 时,我无法真正调试序列化,因此我将此代码添加到 GetCustomDetailReport() 的末尾以捕获错误。
DataContractSerializer ser = new DataContractSerializer(typeof(DataTable), new List<Type> { typeof(DetailLog) });
ser.WriteObject(Stream.Null, data);
当我这样做时,我看到了一个异常
Cannot serialize member ... of type System.Collections.Generic.Dictionary`2 because it implements IDictionary.