2014-10-27 25 views
0

在我的web Api项目中,我使用参数化方法,而不是通过方法名调用。我在我的角码中使用$资源,这个调用完美。使用Web API正确格式化JSON Get()

例如,这让我的联系人列表:

public class LeadsController : ApiController 
{ 
    public IEnumerable<Contact> Get() 
    { 
     var contacts = new ContactRepository(); 

     return contacts.BuildContacts(); 
    } 
} 

我唯一的问题是外壳所以后来我用newtonsoft,不得不返回类型更改为字符串,它的工作

public class LeadsController : ApiController 
{ 
    public string Get() 
    { 
     var contacts = new ContactRepository(); 
     var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; 

     return JsonConvert.SerializeObject(contacts, Formatting.Indented, settings); 
    } 
} 

现在我遇到的问题是角期望数组,但它返回一个对象(字符串),所以我有错误。这里是我的角度

return $resource('http://localhost:33651/api/Leads/', { 
    get: { method: 'GET', isArray: false }, 
    query: { 
     method: 'GET', 
     isArray: true 
    } 
}); 

有没有在我的网页API方法一种方法,我可以返回IEnumerable和已JSON的骆驼情况下,格式正确无误?我应该如何处理我的情况的最佳方式是什么?

感谢您的帮助

回答

1

的Web API已经使用Newtonsoft串行器,所以你只需要进行配置。这些行添加到WebApiConfig.Register方法:

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter; 
    json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); 

,并返回IEnumerable<Contact>代替string的,请看一看这个示例项目https://github.com/maxbrodin/camel-case-serialization-webapi

编辑

+0

确定这可能是有点在我头上。所以我很确定我想在该博客文章中实现最后一个类,并使用它来代替newtonsoft类? – 2014-10-27 20:30:16

+1

@ osiris355没错,尝试添加'JsonNetFormatter'类并将其注册到'Application_Start'中。这将允许您保留'IEnumerable '而不是'string'类型的结果。 'OnWriteToStreamAsync'方法负责json输出。 – 2014-10-27 22:36:43

+0

我正在努力让班级成员遇到麻烦。 FormatterContext不会解决。 http://stackoverflow.com/questions/20095701/the-type-or-namespace-name-formattercontext-could-not-be-found-net-4-5 – 2014-10-27 22:46:10