Karl Eriksson
Karl Eriksson

Reputation: 205

Returning .NET MVC model as JSON results in Bad Gateway

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?

Upvotes: 0

Views: 389

Answers (2)

ediblecode
ediblecode

Reputation: 11971

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/.

Upvotes: 2

sis
sis

Reputation: 142

Have you tried this:

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

Upvotes: 1

Related Questions