tags:

views:

27

answers:

2

When requesting an object for example using REST, is it possible to get the response in json and xml format or do I have to create UriTemplates that are something like:

[WebInvoke(UriTemplate="&format=json?user/{id}", ResponseFormat=WebMessageFormat.Json)]

[WebInvoke(UriTemplate="&format=xml?user/{id}", ResponseFormat=WebMessageFormat.Xml)]

The reason I ask is because I may need one format returned for an app on an android phone for example and another type returned for an app on a laptop.

Also, Can the methods have the same name such as Register or do I have to have one called:

RegisterJSON(User user) and another called RegisterXML(User user)

A: 

Out of the box, you need two separate, distinct methods - one for each response format. Also those methods need to have separate names, since the URL in REST must be unique - therefore, the method names must be unique.

With a bit of clever WCF extensibility coding, you can get dynamic response format as easy as adding an attribute on your service method:

[OperationContract]
[WebGet(UriTemplate = "GetData?param1={i}&param2={s}")]
[DynamicResponseType]
public SampleResponseBody GetData(int i, string s)
{
    return new SampleResponseBody() 
               { 
                  Name = "Test",
                  Value = s, 
                  Time = DateTime.Now.ToShortTimeString() 
               };
}

See that neat [DynamicResponseType] attribute there??

Check out the entire blog post by Damian Mehers: WCF REST Services: Setting the response format based on request's expected type for all the great details!

Update: Unfortunately, it seems the sample code for this article isn't available anymore. Kyle Beyer built on top of Damian's work and published his extended, enhanced version in this blog post, WCF and REST, An approach to using the Content-Type and Accept HTTP Headers for Object Serialization. Excellent stuff.

marc_s
A: 

It is available out of the box in WCF 4 (.NET 4.0). Check AutomaticFormatSelectionEnabled property of WebHttpBehavior. You can also set this property from configuration. I showed the example here.

Ladislav Mrnka