Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a Base64 encoded byte array from a WCF REST service using JSON?

Tags:

json

c#

wcf

I have a simple WCF REST method that will return an image/file/etc in a byte array:

[OperationContract]
[WebGet(UriTemplate = "TestMethod")]
byte[] TestMethod();

The service contract is bound to a webHttpBinding with the following behavior:

<endpointBehaviors>
  <behavior name="webHttpBehavior">
    <webHttp defaultOutgoingResponseFormat="Json" />
  </behavior>
</endpointBehaviors>

The method works fine, except the byte array is formatted like:

[25,15,23,64,6,5,2,33,12,124,221,42,15,64,142,78,3,23]

If I remove the attribute defaultOutgoingResponseFormat="Json", the service defaults to XML formatting, and the result is encoded in Base64 like:

GQ8XQAYFAiEMfN0qD0COTgMX

which saves on data transfer, especially when the data get large.

How can I enable Base64 encoding for the JSON output format?

like image 263
Ryan J. Thompson Avatar asked Aug 21 '12 21:08

Ryan J. Thompson


1 Answers

I faced a similar issue with our company's web service a few months ago. I had to figure out how to send a byte array using json endpoints. Unfortunately there isn't an easy answer. I found two work arounds however and I decided to go with the easiest one. I'll let you decide if either of these are helpful.

Option 1 return a base64 encoded string instead of a byte array:

Microsoft's Convert library easily converts a byte array to a base 64 string and vice versa.

[OperationContract]
[WebGet(UriTemplate = "TestMethod")]
string TestMethod();

public string TestMethod()
{
    byte[] data = GetData();
    return Convert.ToBase64String(data);
}

Your json result would then be something like...

{
    "TestMethodResult":"GQ8XQAYFAiEMfN0qD0COTgMX"
}

Then your client can convert that back to a byte array. If the client is also using C# its as easy as

byte[] data = Convert.FromBase64String("GQ8XQAYFAiEMfN0qD0COTgMX");

If you have an rather large byte array however, as was in our case, the following might be a better option

Option 2 return a stream:

Yes this does mean that you will not be getting json. You are essentially just sending raw data and setting the content header so the client knows how to interpret it. This worked for us because we were simply sending an image to a browser.

[OperationContract]
[WebGet(UriTemplate = "TestMethod")]
Stream TestMethod();

public Stream TestMethod()
{
    byte[] data = GetData();
    MemoryStream stream = new MemoryStream(data);
    WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg"; //or whatever your mime type is
    stream.Position = 0;
    return stream;
}
like image 52
sanpaco Avatar answered Nov 13 '22 09:11

sanpaco