Accepting multiple representations for POST

239 Views Asked by At

I'm getting up to speed with the WCF Web API. I want to expose an endpoint that can accept notes, via the POST method. My issue is, I want to support multiple representations for notes. For example, I might want to accept a note using a custom XML serialization that we're using elsewhere, or as an atom:entry element. I already have formatters that can deserialize these into a Note class (our own custom class) or as a SyndicationItem.

The question comes though, how do I define the method? I've currently got this:

[WebInvoke(UriTemplate = GetNotesUriRoot,Method="POST")]
public HttpResponseMessage PostNote(ObjectContent item,HttpRequestMessage request)

Which fails when starting up:

The service operation 'PostNote' will never receive a value for the input parameter 'item' of type 'ObjectContent'. Ensure that a request HttpOperationHandler has an output parameter with a type assignable to 'ObjectContent'.

I initially tried having two separate methods (with appropriately typed parameters), but they can't share the same endpoint name. The current effort (using ObjectContent) was based on other posts I could find that suggested that it could be a parameter. There is no common base type or interface between Note and SyndicationItem

We're using v0.6.0 of the WCF Web API

2

There are 2 best solutions below

0
On

You need to have a parameter / return type of type Note and your formatters will (de-)serialize it to / from the required representation.

0
On

[WebInvoke(UriTemplate = GetNotesUriRoot,Method="POST")]
public HttpResponseMessage PostNote(Note note)

then in your request the content-type header will determine how the object is deserialised. You don't need to worry about deciding how to deserialise, the decision is made for you, as long as the relevant formatter exists (I've not delved in to formatters yet as json/xml have been enough for me so far)