简体   繁体   English

ASP.NET WEB API序列化:最佳实践

[英]ASP.NET WEB API serialization: best practice

I have a ASP.NET WEB API v2 project with entity framework and when i call the route 我有一个带有实体框架的ASP.NET WEB API v2项目,当我调用路由时

// GET api/People

i have a json serialization error. 我有一个json序列化错误。

So, i have a People entity: 因此,我有一个People实体:

public People()
{
   public int Id { get; set; }
   public string Name{ get; set; }
   ....
   ....
   public virtual ICollection<Role> Role{ get; set; }
   public virtual ICollection<Device> Device { get; set; }
}

and the controller: 和控制器:

// GET api/People
public IEnumerable<People> GetPeople()
{
    var p = db.People.ToList<People>().ToList();
    return p;
}

and, in debug, p count 7 elements and it's correct but i have an error in serialization. 并且,在调试中,p计数7个元素,这是正确的,但是我在序列化中有错误。 I think the problem is the loading of the collection. 我认为问题在于集合的加载。

In WebApiConfig.cs i've put this code: 在WebApiConfig.cs中,我输入了以下代码:

var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling= Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);

So what's the best practice in web api to serialize a complex entity? 那么,Web api序列化复杂实体的最佳实践是什么? I must return an anonymous type instead of the entire People object? 我必须返回匿名类型而不是整个People对象吗?

The error is: 错误是:

{"$id":"1","Message":"An error has occurred.","ExceptionMessage":"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.","ExceptionType":"System.InvalidOperationException","StackTrace":null,"InnerException":{"$id":"2","Message":"An error has occurred.","ExceptionMessage":"Error getting value from 'Tessera' on 'System.Data.Entity.DynamicProxies.Tag_0E0771BC33ADE7B095FF6A8E8DC8501A7DB9907E6F3C703A4EDC71C83D881122'.","ExceptionType":"Newtonsoft.Json.JsonSerializationException","StackTrace":"   in Newtonsoft.Json.Seria.......

this will return json by default, unless you specify text/xml as request accept header 默认情况下,它将返回json,除非您将text/xml指定为请求接受标头

var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM