How should I return 404 from a JsonResult Controller?
Asked Answered
K

1

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?

Kloman answered 8/5, 2015 at 19:25 Comment(0)
A
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);
}
Appendicle answered 8/5, 2015 at 19:39 Comment(1)
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.Menstruation

© 2022 - 2024 — McMap. All rights reserved.