温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何解决ASP.NET MVC 遇到JSON循环调用的问题

发布时间:2020-09-08 11:42:56 来源:亿速云 阅读:178 作者:小新 栏目:编程语言

如何解决ASP.NET MVC 遇到JSON循环调用的问题?这个问题可能是我们日常学习或工作经常见到的。希望通过这个问题能让你收获颇深。下面是小编给大家带来的参考内容,让我们一起来看看吧!

1..Net开源Json序列化工具Newtonsoft.Json中提供了解决序列化的循环引用问题:

方式1:指定Json序列化配置为 ReferenceLoopHandling.Ignore

方式2:指定 JsonIgnore忽略 引用对象

实例1,解决MVC的Json序列化引用方法:

step1:在项目上添加引用 Newtonsoft.Json程序包,命令:Insert-Package Newtonsoft.Json

step2:在项目中添加一个类,继承JsonResult,代码如下:

/// <summary>/// 继承JsonResut,重写序列化方式/// </summary>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,重写Json()方法,代码如下:

public class BaseController : Controller
{public StudentContext _Context = new StudentContext();/// <summary>/// 重写,Json方法,使之返回JsonNetResult类型/// </summary>protected override JsonResult Json(object data, string contentType,
        Encoding contentEncoding, JsonRequestBehavior behavior)
    {return new JsonNetResult
        {
            Data = data,
            ContentType = contentType,
            ContentEncoding = contentEncoding,
            JsonRequestBehavior = behavior
        };
    }
}

step4.向平时一样使用就可以了

//获取列表public JsonResult GetList()
{
    List<student> list = _Context.students.Where(q => q.sno == "103").ToList();//方法1return Json(list);//方法2//return new JsonNetResult() {//    Data=list//};
}

获取的结果,说明,这种方式指定忽略循环引用,是在指定循环级数后忽略,返回的json数据中还是有部分循环的数据

如何解决ASP.NET MVC 遇到JSON循环调用的问题

解决EF Json序列化循环引用方法2,在指定的关联对象上,添加JsonIgnore 方法注释

[JsonIgnore]public virtual ICollection<score> scores { get; set; }

返回结果中,没有关联表数据

如何解决ASP.NET MVC 遇到JSON循环调用的问题

感谢各位的阅读!看完上述内容,你们对如何解决ASP.NET MVC 遇到JSON循环调用的问题大概了解了吗?希望文章内容对大家有所帮助。如果想了解更多相关文章内容,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI