Question

I'm runnning a WCF webservice using JSON formatting as follows. My problem is that the response format is alowas Json or XML but for GetImage I would like to return the image as mime-type image-png. Any idea how to do this in WCF? Thanks in advance.

[ServiceContract]
public interface IEditor
{
    [OperationContract]
    [WebInvoke(Method = "GET", UriTemplate = "/GetImage", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
    byte[] GetImage();

[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "/GetBounds", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
void GetBounds(out Rectangle bounds, out Point[] viewport);
Was it helpful?

Solution

  1. use WebOperationContext.Current

  2. return Stream

Your method should be something like this

[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "/GetImage", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
public Stream GetImage()
{
    var m = new MemoryStream();
    //Fill m

    // very important!!! otherwise the client will receive content-length:0
    m.Position = 0;

    WebOperationContext.Current.OutgoingResponse.ContentType = "image/png";
    WebOperationContext.Current.OutgoingResponse.ContentLength = m.Length;
    return m;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top