【解決方法】C#でWeb APIメソッドからバイト配列を適切に取得するにはどうすればよいですか?


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

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

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

C#
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
   } 

さて、問題はarrayMyMethodが送信するバイトが528バイトであることですが、ここでReadAsByteArrayAsyncを作成した後、サイズが大きくなり(706バイト)、値もおかしくなります。 頭をぶつけるような感じですが、助けていただければ幸いです。

ありがとう

解決策 1

解決策がわかりました:
それ以外の

C#
mybytearray= response.Content.ReadAsByteArrayAsync().Result;

私がやっている:

C#
string result=null;
result = response.Content.ReadAsStringAsync().Result.Replace("\"", string.Empty);
 mybytearray=Convert.FromBase64String(result);

重要なポイントは次のとおりです。
バイト配列をbase64エンコードとして返していました。

コメント

タイトルとURLをコピーしました