1
votes

I have an API which returns a JSON object, one of the attributes of which contains some base64 encoded binary data (a PDF file). I want to use a policy in Azure API Management in front of this API so the response returns just the decoded binary data.

I can decode the binary data into a byte array, but to return it I need to update the response body with the content of that byte array (I've set the content-type header accordingly also). The set-body policy is the one I've tried to use:

<set-body>@{
   var response = context.Response.Body.As<JObject>(true);
   string content = response.Value<string>("content");
   Byte[] bytes = Convert.FromBase64String(content);
   return bytes; // Can't do this!
}</set-body>

The above doesn't work, as the return type for set-body has to be a string. I can't convert the binary data to a string as it will get corrupted by ASCII encoding. I can't directly try to assign the value to context.Response.Body as it is read-only within the policy.

Is there any other way of getting Azure API Management to return my byte array in the response?

3

3 Answers

1
votes

This is now possible exactly as you've written it:

<set-body template="none">@{
    var body = new JObject();
    body["Message"] = "SGVsbG8gV29ybGQ=";
    return Convert.FromBase64String(body["Message"].ToString());
}</set-body>

or without Base64 conversion:

<set-body template="none">@{
    var body = new JObject();
    body["Message"] = "Hello World";
    return Encoding.UTF8.GetBytes(body["Message"].ToString());
}</set-body>

Another interesting thing is, that certificates coming as a byte[] can also be set via policy:

<authentication-certificate body="@(context.Variables.GetValueOrDefault<byte[]>("byteCertificate"))" password="optional-certificate-password" />

See this link: microsoft.com/en-us/azure/api-management/api-management-authentication-policies

1
votes

The response is going to be a string no matter what, so returning the base64 string as is sure would be an option, no?

Another option would be to build a string containing your bytes as hex. For example "0xDEADBEEF".

1
votes

At the moment this is not possible. You must return string and it will be put into message using UTF8 encoding. That is definitely something we need to add.