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

无法使用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();
    }}


慕丝7291255
浏览 645回答 3
3回答

慕村225694

如果您正在使用EF,除了在Global.asax上添加以下代码GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings &nbsp;&nbsp;&nbsp;&nbsp;.ReferenceLoopHandling&nbsp;=&nbsp;Newtonsoft.Json.ReferenceLoopHandling.Ignore;GlobalConfiguration.Configuration.Formatters &nbsp;&nbsp;&nbsp;&nbsp;.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);不要忘记导入using&nbsp;System.Data.Entity;然后您可以返回自己的EF模型就那么简单!
打开App,查看更多内容
随时随地看视频慕课网APP