几个月来,以下Web API 2(简化示例)正确响应
http://localhost/TestApi2/api/tests with this.
[{"Id":1,"Name":"Naples"},{"Id":2,"Name":"Paris"}]
//using Newtonsoft.Json;
namespace TestApi2.Controllers
{
public class PersonsController : ApiController
{
[HttpGet]
[Route("api/tests")]
public HttpResponseMessage GetAll()
{
// This is a dbContext generated from a DatabaseFirst EF Generation
using (var cleanDbContext = new cleanDbEntities())
{
var tests = cleanDbContext.TestTables;
// Return all
return Request.CreateResponse(HttpStatusCode.OK, tests, Configuration.Formatters.JsonFormatter);
}
}
}
}
然后我在项目上更新了我的NuGets 同一个电话回复:
<ExceptionMessage>
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace/>
显然NuGet更新中的某些内容,也许是格式化程序Newtonsoft,无法序列化&#34; var list =&#34;中隐含的列表。列表没问题,因为我可以通过它来检查内容。
经过大量的痛苦和实验后,我更改了查询以显式生成列表,同时保留匿名var目标。
var tests = cleanDbContext.TestTables.ToList();
修改查询以显式生成List修复了该问题。我将此信息发送给Newtonsoft。这是一个很棒的产品。