12

In ASP.NET MVC5 I have a controller with a JsonResult return type.

Depending on parameters I want to return a 404, as this is descriptive of the user requesting non-existent data.

I could throw new HttpException(404, "message") but this feels dirty given the return HttpNotFound() syntax. This doesn't work, of course, because HttpNotFoundResult does not inherit JsonResult

How should I cleanly return 404's from JsonResult controller methods?

Matthew
  • 10,244
  • 5
  • 49
  • 104

1 Answers1

17

All your actions should simply have ActionResult return values. This allows you to return any valid result type, whether that's a JsonResult or HttpNotFoundResult.

public ActionResult Foo()
{
    if (!foos.Any())
    {
        return new HttpNotFoundResult();
    }

    return Json(foos, JsonRequestBehavior.AllowGet);
}
Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • 11
    I'd be careful with saying they "should" because it's really a matter of styling and necessity. Arguing all actions should return ActionResult is like arguing all methods should return `object`. – jamesSampica May 08 '15 at 22:46