How to return anonymous types from WebAPI

September 25, 2013 by Anuraj

.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 = "",
        Url = ""

    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

Copyright © 2024 Anuraj. 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. Powered by Jekyll. Hosted with ❤ by GitHub