c# - 使用 Web API 和 JSON.NET 序列化对象时防止 $id/$ref

标签 c# asp.net-mvc-4 json.net asp.net-web-api

我似乎无法阻止 Web API/JSON.NET 在序列化对象时使用 Newtonsoft.Json.PreserveReferencesHandling.Objects。换句话说,尽管使用了以下设置,但 $id/$ref 始终在序列化对象中使用:

public class MvcApplication : System.Web.HttpApplication {

    protected void Application_Start () {
        WebApiConfig.Register(GlobalConfiguration.Configuration);
    }

}

public static class WebApiConfig {

    public static void Register (HttpConfiguration config) {
        JsonMediaTypeFormatter jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().Single();
        jsonFormatter.UseDataContractJsonSerializer = false;
        jsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
        jsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        jsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None;
    }

}

有什么想法吗?

最佳答案

将其放入 Global.asax 中以配置引用处理。 PreserveReferencesHandling 不应为“全部”

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None;

关于c# - 使用 Web API 和 JSON.NET 序列化对象时防止 $id/$ref,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21046872/

相关文章:

c# - 时间跨度字符串格式

c# - 锁定的 console.writeline 调用工作不正常

c# - docker 应用程序中的 `new HttpRequestMessage(...)` 无法访问互联网?

javascript - MVC Controller 属性无法识别参数的集合

c# - 在 MVC 5 中使用 Entity Framework 6 更新相关数据

c# - .NET Core 项目与 .NET Framework 中为 System.Data.DataTable 生成的 JSON 的变化

c# - 在代码隐藏中动态引用控件(表)

asp.net-mvc - 在 POST 编辑中保存表单的正确方法?

c# - 名称为 'Id' 的成员已存在于 `Model` 上。使用 JsonPropertyAttribute 指定另一个名称

c# - 将对象中的 Json 数组发送到 API