Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 717
Dblock247 Avatar asked Jan 16 '16 21:01

Dblock247


People also ask

How do I return a JSON response in C#?

To return JSON from the server, you must include the JSON data in the body of the HTTP response message and provide a "Content-Type: application/json" response header.

Can we return JSON in ActionResult?

JsonResult is an ActionResult type in MVC. It helps to send the content in JavaScript Object Notation (JSON) format.

What is the correct way to return JSON objects from action methods in ASP.NET MVC?

In your action method, return Json(object) to return JSON to your page. SomeMethod would be a javascript method that then evaluates the Json object returned. ContentResult by default returns a text/plain as its contentType.


1 Answers

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;
    });
like image 129
Oleg Avatar answered Oct 25 '22 12:10

Oleg