How to return anonymous types from WebAPI

Posted by Anuraj on Wednesday, September 25, 2013

.Net .Net 3.0 / 3.5 .Net 4.0 Web API

Sometimes you may required to return anonymous types from your WebAPI functions; I found a situation like this today, where I need to return list of values with a count, which was using to plot some graphs. Initially I thought of creating an class for this purpose with a count property, but later I found a simple solution using anonymous types.

Here is the code snippet.

public HttpResponseMessage Get()
{
    var developer = new
    {
        Name = "anuraj",
        Email = "anuraj.p@dotnetthoughts.net",
        Url = "http://dotnetthoughts.net"
    };

    return Request.CreateResponse(HttpStatusCode.OK, developer);
}

This code will work because the CreateResponse() method has an over load which takes T. But sometimes serialization may create some problem.

This is the Get method and you will get a response like this using Fiddler.

Fiddler - Request and Response values

Note: It is recommended to use content-type as application/json while requesting to this Get method, when I tried with IE, I found a serialization issue.

Happy Programming


Similar Posts


Did you like this article? Share it with your friends

Facebook Twitter Google+ LinkedIn Reddit StumbleUpon



MVP
Subscribe
Archives


Copyright © 2017 - Anuraj P. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Hosted with ❤ by GitHub