views:

249

answers:

1

I've recently started reading about the WebHttpBinding usage in WCF and being able to consume REST services, however, I've been stumped on this one for a bit now.

I'm writing a service that makes a single request to a given api, however, can return one of many responses.

For example, the generic response:

<ActualResponse>
<ResponseItem>
 <Name />
 <Area />
</ResponseItem>
</ActualResponse>

However, if something were invalid in the outgoing request or the responding service itself was experiencing any sort of issue a returning response would be:

<ErrorResponse>
    <Message />
</ErrorResponse>

Pedram Rezaei had a great post on consuming REST services, which is where I borrow most of my information from. From what I can tell, we can create an object as long as the object has serializable attributes defined. The issue being, there's no condition to which class to be created(ErrorResponse/ActualResponse).

I'm unsure if I should be looking at some sort of TryParse functionality that sends the initial request and catches the error if no deserialization can occur or if there is a more elegant approach.

I'm fairly new to the WCF world, so the possibility exists I may be entirely overlooking something!

A: 

I think you can borrow some practice from SOAP, which has a hierarchy like so:

<soap:Envelope>
    <soap:Body>
        ... message contents
    </soap:Body>
</soap:Envelope>

I'm not suggesting that you use SOAP, I'm suggesting that you learn from the design employed by SOAP. What SOAP does is embed the successful (or in your words "actual") response within the Body, or return a soap:Fault within the Body.

a success in SOAP might look like this:

<soap:Envelope>
    <soap:Body>
        <ActualResponse>... </ActualResponse>
    </soap:Body>
</soap:Envelope>

while a fault might look like this:

<soap:Envelope>
    <soap:Body>
        <soap:Fault>... </soap:Fault>
    </soap:Body>
</soap:Envelope>

In your case, you might have this:

<ServiceResponse> 
     <ActualResponse> ... </ActualResponse>
</ServiceResponse>

or

<ServiceResponse> 
     <Fault> ... </Fault>
</ServiceResponse>

And XML Serialization is really good at that. . .

But it sounds like you have no control over the envelope. The fact is that you can get multiple different responses. To handle this, you could wrap the actual response received in a contrived XML envelope, and deserialize the result of that.

If you get <ActualResponse>...</ActualResponse> , wrap it in a deserializable envelope to get something like <ServiceResponse><ActualResponse>...</ActualResponse></ServiceResponse>, then deserialize.

Cheeso