ASP .NET MVC - Json 的循环回路
要解决 Json 的循环回路, 需要先新建一个类
需要先引用 using Newtonsoft.Json;
public class JsonNetResult : JsonResult { public JsonSerializerSettings Settings { get; private set; } public JsonNetResult() { Settings = new JsonSerializerSettings { //这句是解决问题的关键,也就是json.net官方给出的解决配置选项. ReferenceLoopHandling = ReferenceLoopHandling.Ignore }; } public override void ExecuteResult(ControllerContext context) { if (context == null) throw new ArgumentNullException("context"); if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) throw new InvalidOperationException("JSON GET is not allowed"); HttpResponseBase response = context.HttpContext.Response; response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType; if (this.ContentEncoding != null) response.ContentEncoding = this.ContentEncoding; if (this.Data == null) return; var scriptSerializer = JsonSerializer.Create(this.Settings); using (var sw = new StringWriter()) { scriptSerializer.Serialize(sw, this.Data); response.Write(sw.ToString()); } } }
再写个 BaseController 基类方法 继承 Controller
重写 Json 方法
public class BaseController : Controller {/// <summary> /// 重写 Json 方法 /// 避免出现循环引用 /// </summary> /// <param name="data"></param> /// <param name="contentType"></param> /// <param name="contentEncoding"></param> /// <param name="behavior"></param> /// <returns></returns> protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior) { return new JsonNetResult { Data = data, ContentType = contentType, ContentEncoding = contentEncoding, JsonRequestBehavior = behavior }; } }