Web API2序列化异常
本文关键字:异常 序列化 API2 Web | 更新日期: 2023-09-27 18:15:27
我有一个使用EF搭建的web api2应用程序。
我正在尝试序列化以下类(其中包含延迟加载的导航属性):
namespace Models
{
public class Speciality
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int SpecialityId { get; set; }
public string Name { get; set; }
public virtual ICollection<Doctor> Doctors { get; set; }
public virtual ICollection<MedicalFacility> MedicalFacilities { get; set; }
}
}
是我的控制器:
namespace FindAMedicService.Controllers
{
public class SpecialitiesController : ApiController
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: api/Specialities
public IQueryable<Speciality> GetSpeciality()
{
return db.Speciality;
}
}
}
当我尝试访问这个特定的服务以获取"Specialities"列表时,我得到以下错误:
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace/>
<InnerException>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Type 'System.Data.Entity.DynamicProxies.Speciality_DC264D6DBBAF52FB19E27F20DCC47DA1141620CEC0CCAF6E2DEF4D8907FA7C8C' with data contract name 'Speciality_DC264D6DBBAF52FB19E27F20DCC47DA1141620CEC0CCAF6E2DEF4D8907FA7C8C:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies' is not expected. Consider using a DataContractResolver if you are using DataContractSerializer or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to the serializer.
</ExceptionMessage>
<ExceptionType>
System.Runtime.Serialization.SerializationException
</ExceptionType>
<StackTrace>
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeAndVerifyType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, Boolean verifyKnownType, RuntimeTypeHandle declaredTypeHandle, Type declaredType) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithXsiType(XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle objectTypeHandle, Type objectType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle) at WriteArrayOfSpecialityToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , CollectionDataContract ) at System.Runtime.Serialization.CollectionDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle) at System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.DataContractSerializer.WriteObject(XmlWriter writer, Object graph) at System.Net.Http.Formatting.XmlMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content) at System.Net.Http.Formatting.XmlMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__1b.MoveNext()
</StackTrace>
</InnerException>
</Error>
我没有这个错误之前,当我没有两个导航属性在我的专业类(医生,医疗设施)。
任何帮助都是非常感激的。只是一个快速回顾-为什么要返回IQueryable
和您的实体模型作为结果?
在我看来,您应该将您的实体模型转换为仅具有所需属性的DTO +将动作签名更改为IEnumerable<T>
。
序列化器不知道的是如何序列化EF为您的virtual
属性创建的动态代理
请在webconfig中输入以下代码片段:
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreservReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
原因可能是你的导航属性是Interface,所以当你访问服务时,它不知道要使用什么具体类型。把它改成List,看看是否有帮助?
使用Serializable()属性。试试这个:
namespace Models
{
[Serializable]
public class Speciality
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int SpecialityId { get; set; }
public string Name { get; set; }
public virtual ICollection<Doctor> Doctors { get; set; }
public virtual ICollection<MedicalFacility> MedicalFacilities { get; set; }
}
}
最后,最终工作的是禁用ProxyCreationEnabled。
在我的控制器中,我现在有以下代码:
public class SpecialitiesController : ApiController
{
private ApplicationDbContext db = new ApplicationDbContext();
public SpecialitiesController()
{
db.Configuration.ProxyCreationEnabled = false;
}
// GET: api/Specialities
public IQueryable<Speciality> GetSpeciality()
{
return db.Speciality;
}
}
这意味着我将不得不使用.include()来加载任何我想要使用的导航属性。