无法让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的任何想法?
首先,您可以使用IEnumerable
或IEnumerable
作为返回类型而不是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; });
- ASP.NET Core中必需的查询字符串参数
- 在ASP.NET Core MVC API控制器上对AuthorizeAttribute进行unit testing
- ASP.NET 5 / MVC 6 Ajax将模型发布到控制器
- .NET Core中的自定义授权属性
- 如何在ASP.NET Core中解析ConfigureServices中的实例
- EF 7(核心)。 像AddTransient一样创建DBContext
- 如何正确地在MVC6中注入HttpContext
- 无法将数据写入传输。 Vs2017 ASP.net核心脚手架(MSSQL WINDOW 10)
- 基于Http Header值的ASP.NET MVC5 / 6路由