无法让 ASP.NET MVC 6 控制器返回 JSON [英] Cant get ASP.NET MVC 6 Controller to return JSON
问题描述
我有一个 MVC 6 项目,我在其中使用 Fiddler 来测试 Web API.如果我采取以下使用 EntityFramework 7 返回列表的控制器操作.然后 html 将呈现良好.
I have an MVC 6 project in which i am using Fiddler to test out Web API. If i take the following controller action which uses EntityFramework 7 to return a List. Then the html will render fine.
[HttpGet("/")]
public IActionResult Index()
{
var model = orderRepository.GetAll();
return View(model);
}
但是当我尝试返回 Json 响应时,我收到了 502 错误.
But when i try to return a Json response instead i get a 502 error.
[HttpGet("/")]
public JsonResult Index()
{
var model = orderRepository.GetAll();
return Json(model);
}
知道为什么对象没有正确序列化为 json 吗?
Any Idea on why the object isnt serialized into json correctly?
推荐答案
首先你可以使用 IEnumerable
或 IEnumerable
作为返回类型JsonResult
并只返回 orderRepository.GetAll()
.我建议您阅读文章以获取更多信息.
First of all you can use IEnumerable<Order>
or IEnumerable<object>
as return type instead of JsonResult
and return just orderRepository.GetAll()
. I recommend you to read the article fr additional information.
关于错误网关的另一个错误.尝试将最新版本 8.0.2 中的 Newtonsoft.Json
添加到 package.json
中的依赖项并使用
About another error with Bad Gateway. Try to add Newtonsoft.Json
in the latest version 8.0.2 to dependencies in package.json
and to use use
services.AddMvc()
.AddJsonOptions(options => {
options.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
顺便说一句,您可以重现错误HTTP 错误 502.3 - 错误网关",如果我只是在工作代码的返回语句上设置断点并等待足够长的时间,您会描述该错误.因此,您很快就会在许多常见错误中看到错误HTTP 错误 502.3 - 错误网关".
By the way one can reproduce the error "HTTP Error 502.3 - Bad Gateway", which you describes if I just set breakpoint on the return statement of working code and wait long enough. Thus you will see the error "HTTP Error 502.3 - Bad Gateway" very soon on many common errors.
您可以向我们考虑更多有用的序列化选项.例如
You can consider to us more helpful serialization options. For example
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;
});
这篇关于无法让 ASP.NET MVC 6 控制器返回 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!