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

标签 c# asp.net json asp.net-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 模型

就这么简单!

关于c# - 无法使用 Json 序列化 Web API 中的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23098191/

相关文章:

c# - C# 本身是否使用 GPU 进行图形处理?

c# - 使用 OLEDB 连接字符串打开 MS Access 并且无权创建 .ldb 锁定文件

javascript - 如何覆盖由 Asp.Net UpdatePanel 添加(动态)的 Javascript 函数?

ASP.NET MVC 希望我将 SQL Server 数据库文件存储在 App_Data 文件夹中 - 应该吗?

javascript - 使用 Javascript 在 json 中进行查询

json - 在 Golang 中将 JSON 中的字符串解析为枚举

c# - ASP :ListBox Get Selected Items - One Liner?

c# - 文件是空的,我不明白为什么。 Asp.net mvc 文件结果

asp.net - Angular2 HTTP 后 ASP.NET MVC Web API

iOS objectmapper,用数组映射 json