Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF WebInvoke ResponseFormat

I have a WCF restul service and I want to allow the user to choose what request format they want, i have the decorations

    [OperationContract]
    [WebInvoke(Method = "GET", 
        ResponseFormat = WebMessageFormat.Xml, 
        BodyStyle = WebMessageBodyStyle.Wrapped, 
        UriTemplate = "getstreamurl?ch={ch}&format=xml")]
    [WebInvoke(Method = "GET",
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Wrapped,
        UriTemplate = "getstreamurl?ch={ch}&format=json")]

First of, is there a way to specify the ResponseFormat at runtime and take the format in as an argument to the method? From reading around i dont think so... OK next thing The above code is ok and works, but im having a problem, i want to be able to specify a default, so when no format arguement is passed then i just default but if i decorate like so

    [WebInvoke(Method = "GET", 
        ResponseFormat = WebMessageFormat.Xml, 
        BodyStyle = WebMessageBodyStyle.Wrapped, 
        UriTemplate = "getstreamurl?ch={ch})]

    [OperationContract]
    [WebInvoke(Method = "GET",
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Wrapped,
        UriTemplate = "getstreamurl?ch={ch}&format=json")]

Where the XML is the default, if i try to call the service method through the browser it tells me that:

UriTemplateTable does not support multiple templates that have equivalent path as template 'getstreamurl?ch={ch}' but have different query strings, where the query strings cannot all be disambiguated via literal values. See the documentation for UriTemplateTable for more detail

They obviously can be distinguished but it seems that WCF is only reading up to the argument and thats it...Any suggestions?

like image 332
Daniel Avatar asked Jun 17 '09 18:06

Daniel


2 Answers

No, I don't think you can do that programmatically at runtime. What you can do of course if to expose two distinct endpoints from your service - one returning XML, another returning JSON, and then programmatically pick which one to call from your client app.

Marc

Update: as Steve Michelotti correctly points out, this automatic switching between JSON and XML can now be achieved in WCF 4.0. WCF 4.0 has an improved REST support which also includes an Format Message Selection feature, based on HTTP accept headers.

For more info on WCF 4.0's new features, see: A Developer's Introduction to WCF 4.0

like image 196
marc_s Avatar answered Nov 20 '22 15:11

marc_s


You can do this if your rest service is configured automatically select response type.

Then on client request simply add needed header Accept: application/json

like image 22
Regfor Avatar answered Nov 20 '22 16:11

Regfor