Aka*_*hia 5 entity-framework lazy-loading json.net asp.net-mvc-4 asp.net-web-api
JSON序列化(ASP.Net Web API)由于自引用循环而失败(这是一个常见问题,原因:被请求的实体延迟加载子实体,并且每个子实体都有父实体的后引用).
我找到了解决办法,但对我没有帮助:
任何经验都沿着同样的路线/建议?
我尝试了所有建议的解决方案,但没有成功。最终将 JSON.Net Serializer\xe2\x80\x99s DefaultContractResolver 重写为:
\n\npublic class FilterContractResolver : DefaultContractResolver\n{\n Dictionary<Type, List<string>> _propertiesToIgnore;\n\n public FilterContractResolver(Dictionary<Type, List<string>> propertiesToIgnore)\n {\n _propertiesToIgnore = propertiesToIgnore;\n }\n\n protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)\n {\n var property = base.CreateProperty(member, memberSerialization);\n List<string> toIgnore;\n property.Ignored |= ((_propertiesToIgnore.TryGetValue(member.DeclaringType, out toIgnore) || _propertiesToIgnore.TryGetValue(member.DeclaringType.BaseType, out toIgnore)) && toIgnore.Contains(property.PropertyName));\n return property;\n }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n然后创建一个静态类,它根据控制器返回要忽略的属性字典:
\n\npublic static class CriteriaDefination\n{\n private static Dictionary<string, Dictionary<Type, List<string>>> ToIgnore = new Dictionary<string, Dictionary<Type, List<string>>>\n {\n {\n "tblCustomer", new Dictionary<Type, List<string>>{\n {\n typeof(tblCustomer), new List<string>{\n //include all\n }\n },\n {\n typeof(tblOrder), new List<string>{\n "tblCustomer"//ignore back reference to tblCustomer\n }\n }\n }\n },\n {\n "tblOrder", new Dictionary<Type, List<string>>{\n {\n typeof(tblCustomer), new List<string>{\n "tblOrders"//ignore back reference to tblOrders\n }\n },\n {\n typeof(tblOrder), new List<string>{\n //include all\n }\n }\n }\n }\n };\n public static Dictionary<Type, List<string>> IgnoreList(string key)\n {\n return ToIgnore[key];\n }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n在每个控制器内部更改 JSON Formatter,如下所示:
\n\nGlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new FilterContractResolver(CriteriaDefination.IgnoreList("tblCustomer"));\n
Run Code Online (Sandbox Code Playgroud)\n
归档时间: |
|
查看次数: |
4913 次 |
最近记录: |