我正在使用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();
}
}
当涉及从Web Api(或其他任何Web服务)将数据返回给使用者时,我强烈建议不要回传来自数据库的实体。使用模型,您可以控制数据的外观而不是数据库,这是更加可靠和可维护的。这样,您就不必在WebApiConfig中花太多时间来处理格式化程序。您可以只创建一个具有子模型作为属性的UserModel,并摆脱返回对象中的引用循环。这使串行器更加快乐。
同样,如果仅在请求中指定“ Accepts”标头,则通常不必删除格式化程序或受支持的媒体类型。玩弄这些东西有时会使事情变得更加混乱。
例:
public class UserModel {
public string Name {get;set;}
public string Age {get;set;}
// Other properties here that do not reference another UserModel class.
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句