Returning anonymous types with Web API

77,545

Solution 1

This doesn't work in the Beta release, but it does in the latest bits (built from http://aspnetwebstack.codeplex.com), so it will likely be the way for RC. You can do

public HttpResponseMessage Get()
{
    return this.Request.CreateResponse(
        HttpStatusCode.OK,
        new { Message = "Hello", Value = 123 });
}

Solution 2

This answer may come bit late but as of today WebApi 2 is already out and now it is easier to do what you want, you would just have to do:

public object Message()
{
    return new { Message = "hello" };
}

and along the pipeline, it will be serialized to xml or json according to client's preferences (the Accept header). Hope this helps anyone stumbling upon this question

Solution 3

In web API 2 you can use the new IHttpActionResult which is a replacement for HttpResponseMessage and then return a simple Json object: (Similiar to MVC)

public IHttpActionResult GetJson()
    {
       return Json(new { Message = "Hello"});
    }

Solution 4

you can use JsonObject for this:

dynamic json = new JsonObject();
json.Message = "Hello";
json.Value = 123;

return new HttpResponseMessage<JsonObject>(json);

Solution 5

You could use an ExpandoObject. (add using System.Dynamic;)

[Route("api/message")]
[HttpGet]
public object Message()
{
    dynamic expando = new ExpandoObject();
    expando.message = "Hello";
    expando.message2 = "World";
    return expando;
}
Share:
77,545

Related videos on Youtube

Magpie
Author by

Magpie

Updated on July 05, 2022

Comments

  • Magpie
    Magpie almost 2 years

    When using MVC, returning adhoc Json was easy.

    return Json(new { Message = "Hello"});
    

    I'm looking for this functionality with the new Web API.

    public HttpResponseMessage<object> Test()
    {    
       return new HttpResponseMessage<object>(new { Message = "Hello" }, HttpStatusCode.OK);
    }
    

    This throws an exception as the DataContractJsonSerializer can't handle anonymous types.

    I have replaced this with this JsonNetFormatter based on Json.Net. This works if I use

     public object Test()
     {
        return new { Message = "Hello" };
     }
    

    but I don't see the point of using Web API if I'm not returning HttpResponseMessage, I would be better off sticking with vanilla MVC. If I try and use:

    public HttpResponseMessage<object> Test()
    {
       return new HttpResponseMessage<object>(new { Message = "Hello" }, HttpStatusCode.OK);
    }
    

    It serializes the whole HttpResponseMessage.

    Can anyone guide me to a solution where I can return anonymous types within a HttpResponseMessage?

  • CodeMonkeyKing
    CodeMonkeyKing over 11 years
    This does not seem to be the case in the current release. I receive a HTTP 500 when executing something like the above.
  • Snixtor
    Snixtor over 11 years
    Working fine for me in 4.0 RTM.
  • Despertar
    Despertar over 11 years
    An important note, Only the default json serializer can handle serialization of anonymous objects. The default xml serializer will error out so be sure if you return anonymous objects that your clients know to send accept:application/json in header. Browser's like Chrome tend to request xml by default as well so just a heads up..
  • Luiso
    Luiso almost 8 years
    @doker What version of WebApi are you using, I just pasted that code from my controller using VS 2015 and WebApi2
  • jjaskulowski
    jjaskulowski almost 8 years
    5.2.3 and I ended up removing xml formater because most returned objects wouldn't serialize to xml anyway.
  • Luiso
    Luiso almost 8 years
    @doker in your case then when you try to do what I suggested what happens? do you get an Exception?
  • Alexey Matveev
    Alexey Matveev over 5 years
    Best answer for me. I need a way to return slim JSON from Web API Action without producing additional stuff in different places / assemblies. Works like a charm! Thanks.