简体   繁体   中英

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

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?

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM