C# で Web API メソッドからバイト配列を適切に取得するにはどうすればよいでしょうか? 質問する

C# で Web API メソッドからバイト配列を適切に取得するにはどうすればよいでしょうか? 質問する

次のコントローラー メソッドがあります。

[HttpPost]
[Route("SomeRoute")]
public byte[] MyMethod([FromBody] string ID)
{
  byte[] mybytearray = db.getmybytearray(ID);//working fine,returning proper result.
  return mybytearray;
}

呼び出しメソッド(これも別の WebApi メソッドです!)では、次のように記述しました。

private HttpClient client = new HttpClient ();
private HttpResponseMessage response = new HttpResponseMessage ();
byte[] mybytearray = null;
response = client.GetAsync(string.Format("api/ABC/MyMethod/{0}", ID)).Result;
if (response.IsSuccessStatusCode)
{
    mybytearray = response.Content.ReadAsByteArrayAsync().Result;//Here is the problem
} 

ここで問題となるのは、MyMethod送信するバイト配列は 528 バイトですが、作成後ReadAsByteArrayAsync、サイズが大きくなり (706 バイト)、値もおかしくなってしまうことです。

ベストアンサー1

実際、HTTP は「生の」バイナリも処理できます。プロトコル自体はテキスト ベースですが、ペイロードはバイナリにすることができます (HTTP を使用してインターネットからダウンロードするすべてのファイルを参照してください)。

WebApi でこれを行う方法があります。コンテンツとしてStreamContentまたは を使用するだけなByteArrayContentので、多少の手作業が必要になります。

public HttpResponseMessage ReturnBytes(byte[] bytes)
{
  HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
  result.Content = new ByteArrayContent(bytes);
  result.Content.Headers.ContentType = 
      new MediaTypeHeaderValue("application/octet-stream");

  return result;
}

何らかの属性などを使用して同じことを行うことも可能かもしれませんが、方法がわかりません。

おすすめ記事