Saturday, February 18, 2012

ASP.NET Web API: ObjectContent constructor changed

WCF Web API was released as ASP.NET Web API (part of ASP.NET MVC4 Beta) and, as part of this release, there were a few changes for those using the Web API. For instance, this is how we were using the Web API to serialize our object when making a POST or PUT call:
var oc = new ObjectContent<MyClass>(input, new MediaTypeHeaderValue(Constants.ContentTypeXml));
After this week's release, this constructor does not exist. This post on the ASP.Net Forums shows that the constructor is now internal, so one needs an alternative. This is the alternative I found to do the same as above:
HttpRequestMessage<T> request = new HttpRequestMessage<T>();
ObjectContent<T> content = request.CreateContent<T>(operationInput, new MediaTypeHeaderValue(Constants.ContentTypeXml), new MediaTypeFormatterCollection() { new XmlMediaTypeFormatter() }, new FormatterSelector());
Definitely a little more verbose than before, but that solves the problem until the ObjectContent constructor becomes public again in a future release (as mentioned in the forum post).
Post a Comment