ASP.net webapi IHttpActionResult返回复杂的JSON

时间:2017-01-26 13:46:59

标签: c# asp.net json asp.net-web-api

我正在努力寻找一种方法将复杂数据从webapi服务器返回到我的客户端应用程序。基本上返回的列表包含另一个对象的嵌套列表,当我查看来自服务器的响应时,我得到如下错误:

  

发生错误。' ObjectContent`1'类型无法序列化内容类型的响应主体' application / json; charset = utf-8' .System.InvalidOperationException发生错误。使用类型' System.Data.Entity.DynamicProxies.Property_6238A3E9AD216212102B01343C0B28238D354B83E729485520A1EC884FE53A26'检测到自引用循环。路径' 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)      在System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type,Object value,Stream writeStream,Encoding effectiveEncoding)      在System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(类型类型,对象值,流writeStream,编码effectiveEncoding)      在System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(类型类型,对象值,流writeStream,HttpContent内容)      在System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(类型类型,对象值,流writeStream,HttpContent内容,TransportContext transportContext,CancellationToken cancellationToken)   ---从抛出异常的先前位置开始的堆栈跟踪结束---      在System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)      在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)      在System.Web.Http.WebHost.HttpControllerHandler。< WriteBufferedResponseContentAsync> d__1b.MoveNext()

这是发送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 });
    }

1 个答案:

答案 0 :(得分:1)

错误消息表明您的数据包含无法序列化的循环引用。

您可以使用以下内容配置循环引用的行为:

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

您可以在此处找到有关参考循环处理的其他信息: