不能让ASP.NET MVC 6控制器返回JSON [英] Cant get ASP.NET MVC 6 Controller to return JSON
问题描述
我在我使用小提琴手来测试网页API一个MVC 6项目。如果我把它使用的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<对象&gt ;
就像返回类型,而不是 JsonResult
并返回 orderRepository.GetAll()
。我建议您阅读文章 FR的更多信息。
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.
关于使用错误的网关另一个错误。尝试添加 Newtonsoft.Json
在最新版本8.0.2到依赖于的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 - 错误的网关,它描述了你,如果我只是设置工作code的return语句断点,等待足够长的时间。很快在许多常见错误 - 这样,你会看到错误错误的网关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屋!