This project is read-only.

Anonymous types with new HttpClient

Topics: Web Api
Feb 10, 2012 at 9:02 PM

Is it possible to send an anonymous type using the new HttpClient? Creating an ObjectContent throws errors about it not being able to serialize something without a default constructor.

I tried to serialize the object using JSON.NET and then use a StringContent, but my service didn't like that either.

Any suggestions on how to do this without creating redundant POCOs for simple situations? How are other people doing this?

Feb 10, 2012 at 9:16 PM

It should work fine.


var x = new { x = 5 };

response.Content = new ObjectContent(x.GetType(), x);

Feb 10, 2012 at 9:17 PM

What are you saying is your output type for the response? do a type object, I'd say.


public HttpResponseMessage<object> MyServiceAction()

var response = new HttpResponseMessage<object>();
var x = new { x = 5 };

response.Content = new ObjectContent(x.GetType(), x);
return response; 

Feb 10, 2012 at 10:46 PM

Huh. I think I was trying typeof(object) before. But this seems to work. Thanks!


var oc = new ObjectContent(rsvp.GetType(), rsvp, JsonMediaTypeFormatter.DefaultMediaType);



Feb 13, 2012 at 11:06 PM

I'm still seeing issues with this. The specific exception I'm getting is: The 'XmlSerializer' serializer cannot serialize the type '<>f__AnonymousType1`2'.

The code looks something like:

using (var httpClient = new HttpClient())
  var uri = new Uri("/someurl");
  var rsvp = new { Name = "Joe Bob", TotalAttendees = 5 };
  var oc = new ObjectContent(rsvp.GetType(), rsvp);
  var result =  httpClient.PostAsync(uri, oc).Result;

Can I somehow force it to try JSON? Shouldn't this work with XML anyway?


Feb 13, 2012 at 11:10 PM

To use JSON you sent the ContentType to application/json.

To expect JSON, you do .Accept.Clear(); .Accept.Add("application/json")

Try using a different xml serializer.

Formatters.XmlFormatter.UseDataContractSerializer = true;

Feb 13, 2012 at 11:13 PM

HttpContent content = new ObjectContent(contentObject.GetType(), contentObject, "application/json");

client.PostAsync(baseAddress + uri, content).Result;


There is also an overload for the media type formatters, but I don't really know how to get ahold of one for that...
That is how you would send using the data contract serializer instead. 

Feb 14, 2012 at 2:43 PM

Even with the DataContractSerializer, it just doesn't want to work. Can anyone demonstrate a working example and post it?

Feb 14, 2012 at 4:26 PM

How were you planning on accepting the object? As type object and accessing it as a collection?