无法将 ASP.NET MVC 6 控制器转换为 return JSON
Cant get ASP.NET MVC 6 Controller to return JSON
我有一个 MVC 6 项目,我在其中使用 Fiddler 测试 Web API。如果我采取以下使用 EntityFramework 7 到 return 列表的控制器操作。然后 html 将渲染正常。
[HttpGet("/")]
public IActionResult Index()
{
var model = orderRepository.GetAll();
return View(model);
}
但是当我尝试 return 一个 Json 响应时,我收到了 502 错误。
[HttpGet("/")]
public JsonResult Index()
{
var model = orderRepository.GetAll();
return Json(model);
}
知道为什么对象没有正确序列化到 json 吗?
首先,您可以使用 IEnumerable<Order>
或 IEnumerable<object>
作为 return 类型,而不是 JsonResult
和 return 只是 orderRepository.GetAll()
。我建议您阅读 the article 以获取更多信息。
关于 Bad Gateway 的另一个错误。尝试将最新版本8.0.2中的Newtonsoft.Json
添加到package.json
中的依赖项并使用use
services.AddMvc()
.AddJsonOptions(options => {
options.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
顺便说一下,如果我只是在工作代码的 return 语句上设置断点并等待足够长的时间,就可以重现错误 "HTTP Error 502.3 - Bad Gateway"。因此,您很快就会在许多常见错误中看到错误 "HTTP Error 502.3 - Bad Gateway"。
您可以考虑向我们提供更多有用的序列化选项。例如
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;
});
我有一个 MVC 6 项目,我在其中使用 Fiddler 测试 Web API。如果我采取以下使用 EntityFramework 7 到 return 列表的控制器操作。然后 html 将渲染正常。
[HttpGet("/")]
public IActionResult Index()
{
var model = orderRepository.GetAll();
return View(model);
}
但是当我尝试 return 一个 Json 响应时,我收到了 502 错误。
[HttpGet("/")]
public JsonResult Index()
{
var model = orderRepository.GetAll();
return Json(model);
}
知道为什么对象没有正确序列化到 json 吗?
首先,您可以使用 IEnumerable<Order>
或 IEnumerable<object>
作为 return 类型,而不是 JsonResult
和 return 只是 orderRepository.GetAll()
。我建议您阅读 the article 以获取更多信息。
关于 Bad Gateway 的另一个错误。尝试将最新版本8.0.2中的Newtonsoft.Json
添加到package.json
中的依赖项并使用use
services.AddMvc()
.AddJsonOptions(options => {
options.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
顺便说一下,如果我只是在工作代码的 return 语句上设置断点并等待足够长的时间,就可以重现错误 "HTTP Error 502.3 - Bad Gateway"。因此,您很快就会在许多常见错误中看到错误 "HTTP Error 502.3 - Bad Gateway"。
您可以考虑向我们提供更多有用的序列化选项。例如
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;
});