Azure FunctionsでByte配列をなんとかして返す。[C#]
AzureFunctionsでAPIサーバー建ててデータの通信を行っているのですが、JSONでなくByte配列でデータを取りたい事があったのでメモ代わりに残しておきます。
FileContentResultで返す(2019年3月16日追記)
Base64エンコーディングを挟む必要はありませんでした。
コードは至ってシンプルです。
* Azure Functions側
var byteArray = new Byte[]{0,1,2,3}; return new FileContentResult(byteArray);
- クライアント側
FileContentResultもHttpStatusはOKを返します。
var res = await HttpClient.GetAsync("https://example.com/api/example"); if (res.StatusCode == HttpStatusCode.OK){ var byteArray = await res.Content.ReadAsByteArrayAsync() } else ...
Base64エンコーディング
Base64エンコーディングでByte配列を文字列に変換します。
Base64についての詳細は割愛します。
- Azure Functions側
var byteArray = new Byte[]{0,1,2,3}; var baseStr = System.Convert.ToBase64String(byteArray); return new OkObjectResult(baseStr);
- クライアント側
GETメソッドで取得した場合のコードです。
var res = await HttpClient.GetAsync("https://example.com/api/example"); if (res.StatusCode == HttpStatusCode.OK){ var binStr = System.Convert.FromBase64String(await res.Content.ReadAsStringAsync()); } else ...