Search code examples
jsonasp.net-web-apijsonresultasp.net-apicontroller

Return JSON Result from an Api Controller


I'm building an Api Controller and I need to serialize my List to JSON as my action result.but It seems that such statements doesn't work

 return Json(data, JsonRequestBehavior.AllowGet);

How can I achieve this ?


Solution

  • As you mentioned that you are using WEB API, I'm assuming it has the JsonFormatter configured. With that said, the responsibility to convert you action result into a JSON is not of your action but from the Media Type Formatter chosen as part of the Content Negotiation process.

    That said, it's enough for your Action to return the actual List type and the Web API Media Type formatter will take care of formatting it to JSON.

    For example, let's say that data is a List<Foo> where Foo is some type that you created. It is enough for your controller action to be:

    public List<Foo> GetFoo()
    {
        var data = GetListOfFoo();
        return data;
    }