无法让ASP.NET MVC 6 Controller返回JSON

我有一个MVC 6项目,我正在使用Fiddler来测试Web API。 如果我采取以下控制器操作,使用EntityFramework 7返回List。 然后html将呈现正常。

[HttpGet("/")] public IActionResult Index() { var model = orderRepository.GetAll(); return View(model); } 

但是当我尝试返回Json响应时,我得到502错误。

 [HttpGet("/")] public JsonResult Index() { var model = orderRepository.GetAll(); return Json(model); } 

关于为什么对象没有正确序列化为json的任何想法?

首先,您可以使用IEnumerableIEnumerable作为返回类型而不是JsonResult并返回orderRepository.GetAll() 。 我建议你阅读这篇文章的附加信息。

关于Bad Gateway的另一个错误。 尝试将最新版本8.0.2中的Newtonsoft.Json添加到package.json依赖项并使用use

 services.AddMvc() .AddJsonOptions(options => { options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; }); 

顺便说一句,人们可以重现错误“HTTP错误502.3 – 错误的网关”,如果我只是在工作代码的return语句上设置断点并等待足够长的话,你会描述它。 因此,您很快就会在许多常见错误上看到错误“HTTP错误502.3 – 错误网关”。

您可以向我们考虑更有用的序列化选项。 例如

 services.AddMvc() .AddJsonOptions(options => { // handle loops correctly options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; // use standard name conversion of properties options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // include $id property in the output options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects; });