.Net MVC5异步请求Entity Framework 无限循环解决方法

.Net MVC5异步请求Entity Framework 无限循环解决方法

  Entity Framework 存在一对多、多对多之间的关系,相互依赖,在返回JSON数据时往往会出现相互引用造成的无限循环问题,对于第三方提供的json序列还通过特性、序列化配置可以解决掉无限循环的问题,因此我们可以利用第三方库解决掉MVC返回JSON无限循环的问题。

  我们可以利用Newtonsoft.Json 的JsonSerializerSettings类进行序列化的设置

  .Net MVC5异步请求Entity Framework 无限循环解决方法

  对于ReferenceLoopHandling枚举类型

 #region 程序集 Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed
// E:\VsGit\DigitizationPlatform\dll\Newtonsoft.Json.dll
#endregion namespace Newtonsoft.Json
{
//
// 摘要:
// Specifies reference loop handling options for the Newtonsoft.Json.JsonSerializer.
public enum ReferenceLoopHandling
{
//
// 摘要:
// Throw a Newtonsoft.Json.JsonSerializationException when a loop is encountered.
Error = ,
//
// 摘要:
// Ignore loop references and do not serialize.
Ignore = ,
//
// 摘要:
// Serialize loop references.
Serialize =
}
}

  我们可以设置JsonSerializerSettings

           JsonSerializerSettings set = new JsonSerializerSettings();
set.Formatting = Formatting.Indented;
set.DateFormatString = "yyyy-MM-dd HH:mm:ss";
//set.MaxDepth = 10;
set.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

  这样我们便可以解决JsonResult返回JSON无限循环问题了

重写MVC -> JsonResult

 using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc; namespace Goldwind.Framework.Web.OverrideExtension
{
public class MyJsonResult: JsonResult
{
public MyJsonResult() { }
public MyJsonResult(object Data) {
this.Data = Data;
}
public MyJsonResult(object Data, JsonRequestBehavior JsonRequestBehavior = JsonRequestBehavior.DenyGet) :this(Data){
this.JsonRequestBehavior = JsonRequestBehavior;
}
public MyJsonResult(object Data, string ContentType,Encoding ContentEncoding = null, JsonRequestBehavior JsonRequestBehavior = JsonRequestBehavior.DenyGet) :this(Data,JsonRequestBehavior) {
this.ContentType = ContentType;
if(ContentEncoding != null)
{
this.ContentEncoding = ContentEncoding;
}
}
public override void ExecuteResult(ControllerContext context)
{
if(this.JsonRequestBehavior == JsonRequestBehavior.DenyGet
&& string.Compare(context.HttpContext.Request.HttpMethod,"Get",true) == )
{
throw new InvalidOperationException();
}
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = string.IsNullOrEmpty(this.ContentType) ?
"application/json" : this.ContentType;
if(this.ContentEncoding != null)
{
response.ContentEncoding = this.ContentEncoding;
}
if(null != this.Data)
{
JsonSerializerSettings set = new JsonSerializerSettings();
set.Formatting = Formatting.Indented;
set.DateFormatString = "yyyy-MM-dd HH:mm:ss";
//set.MaxDepth = 10;
set.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
response.Write(JsonConvert.SerializeObject(this.Data,set));
}
}
}
}
上一篇:Web服务器(容器)请求常见的错误及其解决方法


下一篇:Android进阶(二十八)上下文菜单ContextMenu使用案例