c# - 无法使用 Json 序列化 Web API 中的响应

我正在使用 ASP.NET MVC 5 Web Api。我想咨询我所有的用户。

我写了 api/users 并收到了这个:

"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'"

在 WebApiConfig 中,我已经添加了这些行:

HttpConfiguration config = new HttpConfiguration();
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; 

但还是不行。

我的返回数据函数是这样的:

public IEnumerable<User> GetAll()
{
    using (Database db = new Database())
    {
        return db.Users.ToList();
    }
}

最佳答案

如果您使用的是 EF,除了在 Global.asax 上添加以下代码

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings
    .ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters
    .Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);          

别忘了导入

using System.Data.Entity;

然后您可以返回自己的 EF 模型

就这么简单!

https://stackoverflow.com/questions/23098191/

相关文章:

javascript - 在 DOM 中嵌入任意 JSON 的最佳实践?

javascript - 将json数据转换为html表

c# - 如何从 JSON 字符串自动生成 C# 类文件

c# - ASP.Net Core 中的 JSON 序列化/反序列化

javascript - 嵌套的 JSON 对象 - 我必须对所有内容都使用数组吗?

jquery - 如何检查值是否为 JSON 对象?

javascript - 将 Javascript 对象编码为 Json 字符串

python - Python中的字符串到字典

ruby-on-rails - 将 json 格式的键值对转换为以符号为键的 ruby​​ 哈希的最

json - 以友好的方式获取ffmpeg信息