小编典典

无法获得ASP.NET MVC 6控制器以返回JSON

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的任何想法?


阅读 259

收藏
2020-07-27

共1个答案

小编典典

首先,您可以使用IEnumerable<Order>IEnumerable<object>作为return类型来代替JsonResultand
return just
orderRepository.GetAll()。我建议您阅读有关其他信息的文章

关于Bad Gateway的另一个错误。尝试将Newtonsoft.Json最新版本8.0.2 添加到依赖项中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;
    });
2020-07-27