为了账号安全,请及时绑定邮箱和手机立即绑定

无法使用Json在Web API中序列化响应

无法使用Json在Web API中序列化响应

C#
慕丝7291255 2019-08-26 18:48:11
无法使用Json在Web API中序列化响应我正在使用ASP.NET MVC 5 Web Api。我想咨询我的所有用户。我写了api/users,我收到了这个:“'ObjectContent`1'类型无法为内容类型'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();     }}
查看完整描述

3 回答

?
慕村225694

TA贡献1880条经验 获得超4个赞

如果您正在使用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模型

就那么简单!


查看完整回答
反对 回复 2019-08-26
  • 3 回答
  • 0 关注
  • 644 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信