我正在使用ASP.NET MVC5WebApi。我想咨询我所有的用户。
我写了api/users,我收到了这样的信息:
“'ObjectContent`1‘类型无法序列化内容类型'application/json;字符集=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();
    }
}发布于 2014-04-16 11:12:06
当涉及到从Web Api (或任何其他web服务)向使用者返回数据时,我强烈建议不要传递来自数据库的实体。使用模型更可靠、更易于维护,在模型中您可以控制数据的外观,而不是数据库。这样,您就不必在WebApiConfig中花费太多时间处理格式化程序。您可以只创建一个将子模型作为属性的UserModel,并去掉返回对象中的引用循环。这使得序列化程序更加令人满意。
此外,如果您只是在请求中指定“Accept”标头,则没有必要删除格式化程序或支持的媒体类型。玩弄这些东西有时会让事情变得更加混乱。
示例:
public class UserModel {
    public string Name {get;set;}
    public string Age {get;set;}
    // Other properties here that do not reference another UserModel class.
}发布于 2015-03-01 09:08:40
如果您正在使用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模型
就这么简单!
发布于 2015-07-04 21:40:24
给出正确的答案是一种方法,然而,当你可以通过一个配置设置来修复它时,这是一种过度杀伤力。
最好在dbcontext构造函数中使用它
public DbContext() // dbcontext constructor
            : base("name=ConnectionStringNameFromWebConfig")
{
     this.Configuration.LazyLoadingEnabled = false;
     this.Configuration.ProxyCreationEnabled = false;
}https://stackoverflow.com/questions/23098191
复制相似问题