0

I have created a web app from the .NET Web Application template. This app should display heroes and their superpowers.

This is my controller method:

public IActionResult GetHero(int id)
    {
        if (!ModelState.IsValid)
        {
            return HttpBadRequest(ModelState);
        }

        Hero hero = _context.Hero.Include(m => m.SuperPowers).Single(m => m.Id == id);

        if (hero == null)
        {
            return HttpNotFound();
        }

        return Json(hero);
    }

And this is my model:

public class Hero
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public virtual ICollection<SuperPower> SuperPowers { get; set; }
}

If I use

return Json(hero);

like in the controller code above I get a "Bad Gateway" error but if I use

return View(hero);

I can display the hero and the related superpowers in a view that I created.

What am I doing wrong?

NinjaDeveloper
  • 1,620
  • 3
  • 19
  • 51
Karl Eriksson
  • 205
  • 4
  • 12
  • Try remove your breakpoints (http://stackoverflow.com/questions/34420397/handling-json-circular-reference-exception-in-asp-net-5) – Tonio Jul 26 '16 at 12:49
  • A little of topic but 'Hero` class is not considered as a `Model` but rather as a data structure – dios231 Jul 26 '16 at 12:57
  • Should your action not be: `public JsonResult GetHero(int id)`? – pookie Aug 10 '16 at 21:08

2 Answers2

2

Try:

return Json(hero, JsonRequestBehavior.AllowGet);

See this answer for why this is important. GET requests are deny by default:

By default, the ASP.NET MVC framework does not allow you to respond to an HTTP GET request with a JSON payload. If you need to send JSON in response to a GET, you'll need to explicitly allow the behavior by using JsonRequestBehavior.AllowGet as the second parameter to the Json method. However, there is a chance a malicious user can gain access to the JSON payload through a process known as JSON Hijacking. You do not want to return sensitive information using JSON in a GET request. For more details, see Phil's post at http://haacked.com/archive/2009/06/24/json-hijacking.aspx/.

Community
  • 1
  • 1
ediblecode
  • 11,701
  • 19
  • 68
  • 116
  • just `Json` `return JsonResult(hero, JsonRequestBehavior.AllowGet);` ? – Tonio Jul 26 '16 at 12:52
  • I get "Cannot resolve symbol JsonRequestBehavior", however this does not work either: return Ok(hero); – Karl Eriksson Jul 26 '16 at 12:56
  • @KarlEriksson It's part of the `System.Web.Mvc` namespace so it should resolve: https://msdn.microsoft.com/en-us/library/system.web.mvc.jsonrequestbehavior(v=vs.118).aspx – ediblecode Jul 26 '16 at 12:57
1

Have you tried this:

services.AddMvc()
    .AddJsonOptions(options => {
        options.SerializerSettings.ReferenceLoopHandling =
            Newtonsoft.Json.ReferenceLoopHandling.Ignore;
    });
sis
  • 142
  • 13