zoukankan      html  css  js  c++  java
  • webapi修改tt模板给字段添加JsonIgnore特性解决转换json循环引用问题

    0.问题描述

    EF生成的model带有导航属性,则json序列化会报循环引用错误,尝试如下

    protected void Application_Start()
    {
    GlobalConfiguration.Configure(WebApiConfig.Register);

    ////config.Formatters.JsonFormatter.MediaTypeMappings.Add(new System.Net.Http.Formatting.QueryStringMapping("datatype", "json", "application/json"));/*http://www.cnblogs.com/mirrortom/p/5931573.html*/

    GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();//清除xml序列化

    //HttpConfiguration config = GlobalConfiguration.Configuration;
    ////config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
    //config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;

    }

    均无法解决.经搜索发现可以修改tt模板,给字段添加JsonIgnore特性

    1.观察edmx生成的model字段

    发现导航属性都是virtual,并且标记有特性[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]

    2.修改tt模板,添加JsonIgnore特性

    找到edmx文件下的.tt文件

    搜索[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]

    并在此行之上添加一行

    [Newtonsoft.Json.JsonIgnore]

    添加后

    最终试验出需加载foreach里面if判断之前

    <#
    foreach (var navigationProperty in navigationProperties)
    {
    #>
    [System.Xml.Serialization.XmlIgnore]
    [Newtonsoft.Json.JsonIgnore]
    <#
    if (navigationProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many)
    {
    #>

    3.项目添加NewtonSoftJson.dll的引用并编译

    此时controller里直接返回db.Table1.ToList();不会发生循环引用

    From:http://www.cnblogs.com/xuejianxiyang/p/6204111.html

  • 相关阅读:
    常用linux命令及其设置
    shell脚本编写步骤及其常用命令和符号
    浏览器访问php脚本通过sendmail用mail函数发送邮件
    windows server 定期备份数据库脚本
    图片垂直水平居中
    "!function",自执行函数表达式
    jQuery(function(){})与(function(){})(jQuery) 的区别
    在Windows Server 2019通过Docker Compose部署Asp.Net Core
    Redis集群同步问题
    webapi跨域使用session
  • 原文地址:https://www.cnblogs.com/xuejianxiyang/p/6204111.html
Copyright © 2011-2022 走看看