Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

c# - Cant get ASP.NET MVC 6 Controller to return JSON

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);
}

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);
}

Any Idea on why the object isnt serialized into json correctly?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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;
    });

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;
    });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...