我不确定我在这里做错了什么,但现在已经有几天我试图解决这个问题,但仍然没有运气。
我有个这样的模特:
public class Event
{
public int Id {get;set;}
public string EventName {get;set;}
public DateTime StartTime{get;set;}
public DateTime FinishTime {get;set;}
}然后我有了这样一个web Api方法:
[HttpGet]
public IQueryable GetTimes()
{
var times = context.Events.where(x => x.EventName == "even name").Select(x => x new{
x.Id,
x.EventName,
StartTime = x.StartTime.ToShortTimeString(), // just getting time only
FinishTime = x.FinishTime.ToShortTimeString() // just getting time only
});
}当我运行我的项目时,我会得到以下错误:
ArrayOf_x003C__x003E_f__AnonymousType0Ofintstringstringstringstringdoubledoublestring:http://schemas.datacontract.org/2004/07/‘是预料不到的。如果您正在使用DataContractResolver或将任何类型静态地添加到已知类型列表中,请考虑使用DataContractSerializer,例如,使用KnownTypeAttribute属性或将它们添加到传递给序列化程序的已知类型列表中。
我以前从未见过这个错误,我不太确定如何处理这个错误。
我还意识到,例如,当我运行一个测试时,如果我在该方法中执行以下操作:
x.Id,
x.EventName,
StartTime = "12.30", // this works fine and no error is thrown.
FinishTime = "16.30"
//also the following works fine:
x.Id,
x.EventName,
x.StartTime,
x.FinishTime, // this works fine obviously i only need the time only这是怎么引起的,我该怎么解决呢?
发布于 2016-05-20 11:44:04
出现此问题是因为用于反序列化结果的客户端的DataContractSerializer需要一个特定类型的数组,而服务器则发出一个匿名类型的数组。您需要在服务器和客户端上使用相同的类型,或者使用相同数据契约的两个类型(这就是生成的代理类VS创建工作的方式)。
尝试创建一个数据传输对象(DTO)类,以便在客户端和服务器上使用。
[DataContact]
public class EventDTO {
[DataMember]
public int Id { get; set; }
[DataMember]
public string EventName { get; set; }
[DataMember]
public TimeSpan StartTime { get; set; }
[DataMember]
public TimeSpan EndTime {get;set;}
}你的get方法看起来就像
[HttpGet]
public IQueryable<EventDTO> GetTimes()
{
return context.Events.where(x => x.EventName == "even name")
.Select(x => x new EventDTO
{
Id = x.Id,
EventName = x.EventName,
StartTime = x.StartTime.TimeOfDay,
FinishTime = x.FinishTime.TimeOfDay
});
}确保在客户端上对反序列化器使用相同的类型。
https://stackoverflow.com/questions/37345686
复制相似问题