11

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?

Dblock247
  • 6,167
  • 10
  • 44
  • 66
  • Can you add some network data of the request and response from Fiddler? – user700390 Jan 16 '16 at 21:38
  • Since you get a 502, there’s an error on the server side. So debug the project and look at the logs. – poke Jan 16 '16 at 21:40
  • It says 502 Bad Gateway HTTP/1.1 502 Bad Gateway Cache-Control: private Content-Type: text/html; charset=utf-8 Server: Kestrel X-SourceFiles: =?UTF-8?B?WjpcRG9jdW1lbnRzXFZpc3VhbCBTdHVkaW8gMjAxNVxQcm9qZWN0c1xKZW5Tb2xvXHNyY1xKZW5Tb2xvXHd3d3Jvb3Q=?= X-Powered-By: ASP.NET Date: Sat, 16 Jan 2016 23:16:58 GMT Content-Length: 4939 @poke – Dblock247 Jan 16 '16 at 23:18
  • 1
    You can just use `public IEnumerable` or `public IEnumerable` instead of `public JsonResult` and return model. I think that [the link](https://docs.asp.net/projects/mvc/en/latest/migration/migratingfromwebapi2.html) will answer all your questions. – Oleg Jan 17 '16 at 00:16
  • @Oleg I have tried IEnumberable and still no luck. I did notice that in fiddler the content types Says text/html. Could this be the reason. Shouldnt ObjectResult change the content type to json? – Dblock247 Jan 17 '16 at 01:54
  • @Oleg I have narrowed the problem down even further. It seems that the .Include(o => = o.User) statement in my repository is making trouble for the serialization to json. If I take that out it seems to work fine. But with it in it doesn't work. Any idea how to correct the problem? – Dblock247 Jan 17 '16 at 02:06
  • Can you check what is your JSON output on the server side which is being sent across to client? – Ankit Vijay Jan 17 '16 at 02:24
  • @AnkitVijay If i set a break point on the return in the action i can inspect the model. It has everything that the Entity should have. They only thing i can notices is they may be a circular reference going on. It gets the order and that order has a user and that users has a List of order which have the user. It seem like that may be causing confusion. Is there a way to stop it from the recursion it is doing? – Dblock247 Jan 17 '16 at 02:36
  • Circular reference always has been issue with JSON. Try out this link for circular reference to see if it helps: http://stackoverflow.com/questions/2002940/json-and-circular-reference-exception – Ankit Vijay Jan 17 '16 at 02:40

1 Answers1

21

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;
    });
Oleg
  • 220,925
  • 34
  • 403
  • 798
  • Thank you that works. Are there options for xml as well? – Dblock247 Jan 17 '16 at 17:25
  • 1
    @Dblock247: MVC don't returns typically XML data. The settings are specific settings of `Newtonsoft.Json` , which is default JSON serializer in ASP.NET 5. – Oleg Jan 17 '16 at 17:31
  • Thank you for the info. Can you recommend an XML Serializer? – Dblock247 Jan 17 '16 at 18:30
  • @Dblock247: First of all you should add `"Microsoft.AspNet.Mvc.Formatters.Xml"`. Then you have the formatters which you can use to configure Mvc for usage of Xml as input or output format. You can try to implement yourself and to ask *new question* if you would have problems. – Oleg Jan 17 '16 at 19:56
  • @Dblock247: I see that you never used voting before. It's really important right, which allows gives tips for searching that the content is helpful. It helps other visitors to find the answer/question. See [here](http://stackoverflow.com/help/why-vote) for example. You have right to vote about 30 answers **per day**. You should active use the right if you want help other. – Oleg Jan 17 '16 at 20:01
  • Didn´t work for 5.0 .Net Api – Alexandre Ribeiro Oct 04 '21 at 09:12