以前都是到处看博客,今天小菜也做点贡献,希望能帮到大家.
废话不多说,直接进入正题.
用过.net MVC的同学应该都被json序列化报循环引用错误这个问题骚扰过.网上有一些解决办法,但是都治标不治本.如在引发异常的属性上加上[ScriptIgnore]或者[JsonIgnore],又或者用db.Configuration.ProxyCreationEnabled = false;这些解决办法都存在问题且需要多处修改并且测试.本小菜之前一直被其骚扰,就在前两天我决定一定要找到比较优的解决办法,google一顿查,各种查,终于在一个老外的文章中找到办法,但是当时光顾考代码看来着忘记链接了....,核心思想就是用json.net替换mvc默认的json序列化类,因为json.net官方给出了解决循环引用的配置选项.
step1 在项目上添加Newtonsoft.Json引用
step2 在项目中添加一个类,继承JsonResult,代码如下
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()); } } }
step3 在项目中新建一个BaseController,继承Controller类,然后重写Controller中的json方法,代码如下
public class BaseController : Controller { protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior) { return new JsonNetResult { Data = data, ContentType = contentType, ContentEncoding = contentEncoding, JsonRequestBehavior = behavior }; } }
step 4 在你自己的controller类中,继承之前的BaseController,然后使用示例如下
[HttpPost] public JsonResult GetUserList() { try { User user = UserHelper.GetCurrentUser(); List<User> users = userService.GetCompanyUsers(user.Units.FirstOrDefault().ID,user.ID); //此时json方法会调用你重写的json方法 return Json(users); } catch (Exception ex) { return Json(CommonException.GetError(ex)); } }
时间: 2024-10-20 20:32:47