gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:42:18 34 4
gpt4 key购买 nike

我正在使用 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/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com