The usage of Extending Encoders and Serializers (see http://msdn.microsoft.com/en-us/library/ms733092.aspx) or other methods of Extending WCF like usage of DataContractSerializerOperationBehavior
is very interesting, but for your special problem there are easier solution ways.
If you already use Message
type to return the results an use WCF4 you can do something like following:
public Message UpdateCity(string code, City city)
{
MyResponseDataClass message = CreateMyResponse();
// use JSON.NET to serialize the response data
string myResponseBody = JsonConvert.Serialize(message);
return WebOperationContext.Current.CreateTextResponse (myResponseBody,
"application/json; charset=utf-8",
Encoding.UTF8);
}
In case of errors (like HttpStatusCode.Unauthorized
or HttpStatusCode.Conflict
) or in other situations when you need to set a HTTP status code (like HttpStatusCode.Created
) you can continue to use WebOperationContext.Current.OutgoingResponse.StatusCode
.
As an alternative you can also return a Stream
(see http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-web.aspx and http://msdn.microsoft.com/en-us/library/ms732038.aspx) instead of Message
to return any data without additional default processing by Microsoft JSON serializer. In case of WCF4 you can use CreateStreamResponse
(see http://msdn.microsoft.com/en-us/library/dd782273.aspx) instead of CreateTextResponse
. Don’t forget to set stream position to 0 after writing in the stream if you will use this technique to produce the response.