简体   繁体   English

ASP.net webapi IHttpActionResult 返回复杂的 JSON

[英]ASP.net webapi IHttpActionResult return complex JSON

I'm battling to find a way to return complex data to my client application from the webapi server.我正在努力寻找一种方法将复杂数据从 webapi 服务器返回到我的客户端应用程序。 Basically the returned list contains nested lists of another object, when I look at the response from the server I get errors as below:基本上返回的列表包含另一个对象的嵌套列表,当我查看来自服务器的响应时,我收到如下错误:

An error has occurred.The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json;发生错误。“ObjectContent`1”类型未能序列化内容类型“application/json;”的响应正文; charset=utf-8'.System.InvalidOperationExceptionAn error has occurred.Self referencing loop detected with type 'System.Data.Entity.DynamicProxies.Property_6238A3E9AD216212102B01343C0B28238D354B83E729485520A1EC884FE53A26'. charset=utf-8'.System.InvalidOperationException发生错误。检测到类型为'System.Data.Entity.DynamicProxies.Property_6238A3E9AD216212102B01343C0B28238D354B83E7294855824A3FE3FE1的自引用循环Path 'propertyDataTypes[0].Properties[0].PropertyDataType.Properties'.Newtonsoft.Json.JsonSerializationException at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CheckForCircularReference(JsonWriter writer, Object value, JsonProperty property, JsonContract contract, JsonContainerContract containerContract, JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType) at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType) at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding) at System.Net.Http.Formatting.Jso路径 'propertyDataTypes[0].Properties[0].PropertyDataType.Properties'.Newtonsoft.Json.JsonSerializationException at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CheckForCircularReference(JsonWriter 编写器,对象值,JsonProperty 属性,JsonContract 合同,JsonContainerContractPropertyContract 容器) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member)在 Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType) at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding EffectiveEncoding) at System.Net.Http。格式化.Jso nMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding) at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content) at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.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() nMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding EffectiveEncoding) at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content) at System.Net.Http.Formatting。 BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancelationToken) --- 上一个抛出异常的位置的堆栈跟踪结束---在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)在 System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__1b.MoveNext()

This is my server code sending the JSON response:这是我发送 JSON 响应的服务器代码:

    [Authorize]
    [HttpGet]
    [Route("api/propertydatatype/all")]
    public IHttpActionResult GetAllPropertyDataTypes()
    {
        var result = propertySVC.GetDataTypes().ToList();
        var config = new MapperConfiguration(cfg => {
            cfg.CreateMap<PropertyDataType, PropertyDataTypeModel>();
        });
        IMapper mapper = config.CreateMapper();
        var propertyDataTypes = mapper.Map<List<PropertyDataType>, List<PropertyDataTypeModel>>(result);
        return this.Content(HttpStatusCode.OK, new { propertyDataTypes = propertyDataTypes });
    }

The error message indicates that your data contains a circular reference that cannot be serialized.该错误消息表明您的数据包含无法序列化的循环引用。

You can configure the behavior on circular references with something like that:您可以使用以下内容配置循环引用的行为:

System.Web.Http.GlobalConfiguration.Configure(config =>
{
    config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; 
});

You can find additional information on reference loop handling here:您可以在此处找到有关参考循环处理的其他信息:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM