WCF - Dynamically Change WebResponseFormat

Posted by Brandon on Stack Overflow See other posts from Stack Overflow or by Brandon
Published on 2010-03-30T14:31:34Z Indexed on 2010/03/30 14:33 UTC
Read the original article Hit count: 352

Filed under:
|
|
|

Is there a way to dynamically change the WebResponseFormat on a method given a parameter passed by the client? I default my WebResponseFormat to XML, but I want to give the client the opportunity to specify a format as JSON or XML and if none is specified, default to XML.

Currently I am doing the following:

[WebGet(UriTemplate = "objects", BodyStyle = WebMessageBodyStyle.Bare)]
[OperationContract]
List<SampleObject> GetObjects();

The user can call it via:

http://localhost/rest/myservice/objects

They then can specify a format by doing:

http://localhost/rest/myservice/objects?format=json

The problem is that when I try to set the response content type via:

WebOperationContext.Current.OutgoingResponse.ContentType = "application/json";

That just returns the XML but the browser attempts to process it like a JSON object instead of serializing the response as JSON.

Is this even possible with .NET 3.5 outside of using a Stream as the return value and serializing the response myself? If not, is there a better solution?

© Stack Overflow or respective owner

Related posts about wcf

Related posts about .NET