WCF InvalidDataContractException:“;类型不能被序列化";但是被正确地标记
本文关键字:quot 正确地 序列化 InvalidDataContractException 类型 不能 WCF | 更新日期: 2023-09-27 18:24:17
我得到一个InvalidDataContractException:
无法序列化类型"LicenseWatchingServiceLibrary.LicenseInfoContainerExpiring"。考虑标记它[…]
但它已经被标记(参见代码)。我已经搜索过了,但我找到的解决方案都不适合我。WCF在这里用于在Windows服务和ui应用程序之间进行通信。部分代码:
引发异常的位,位于windows wcf服务应用程序中:
private void Run()
{
//[...]
List<LicenseInfoContainerExpiring> expiringLicenses;
List<LicenseInfoContainerUntrusted> untrustedLicenses;
readLicenseInfoLists(out expiringLicenses, out untrustedLicenses, out warningNeeded);
if (warningNeeded)
{
LWSProxy.WatchLicenses(expiringLicenses, untrustedLicenses); //breaks here
}
}
类库内部的接口
[ServiceContract]
public interface ILicenseWatchingServiceUXHost
{
[OperationContract]
void WatchLicenses(List<LicenseInfoContainerExpiring> elcs, List<LicenseInfoContainerUntrusted> ulcs);
}
LicenseInfoContainerExpiring.cs,也位于类库中:(所有这些,以防我忘了什么)
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.Serialization;
using System.ServiceModel;
namespace LicenseWatchingServiceLibrary
{
[DataContract]
public partial class LicenseInfoContainerExpiring : ILicenseInfoContainer
{
#region precode
#region properties
[DataMember]
public string licenseName { get; private set; }
[DataMember]
public DateTime licenseExpirationDate { get; private set; }
[DataMember]
public int licenseDaysUntilExpired { get; private set; }
[DataMember]
public string licenseType { get; private set; }
[DataMember]
public string licenseActivationID { get; private set; }
#endregion
#region objects
[DataMember]
private CultureInfo ci = new CultureInfo("en-US");
#endregion
#endregion
#region constructor
public LicenseInfoContainerExpiring() { }
public LicenseInfoContainerExpiring(string name, string ID, string type, string expirationDate)
{
licenseName = name;
licenseType = type;
licenseActivationID = ID;
//calculate expiration
if (expirationDate != "permanent")
{
licenseDaysUntilExpired = (DateTime.ParseExact(expirationDate, "dd-MMM-yyyy", ci) - DateTime.Now.Date).Days;
}
else
{
licenseDaysUntilExpired = 9999999;
}
}
#endregion
}
}
您有带有私有setter的数据成员。这样就不可能在反序列化时设置其值。也要公开二传手。
请记住,数据契约在反序列化时甚至不调用默认构造函数就被实例化了。
namespace LicenseWatchingServiceLibrary
{
[DataContract]
public partial class LicenseInfoContainerExpiring : ILicenseInfoContainer
{
#region precode
#region properties
[DataMember]
public string licenseName { get; set; }
[DataMember]
public DateTime licenseExpirationDate { get; set; }
// ...
}
}
添加KnowType:
[DataContract]
[KnownType(typeof(GregorianCalendar))]
public partial class LicenseInfoContainerExpiring : ILicenseInfoContainer
{}