如何从C#中的Web Api方法正确获取字节数组? [英] How to Get byte array properly from an Web Api Method in C#?

查看:238
本文介绍了如何从C#中的Web Api方法正确获取字节数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下控制器方法:



I have the following controller method:

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



现在在调用方法(这也是另一个WebApi方法!)中,我写的是这样的:




Now in the calling method(thats also another WebApi method!),I have written like this:

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字节),并且值也被放大了。有点磕磕碰碰我的头,任何帮助都会受到赞赏。



谢谢


Now, the problem is the byte arrayMyMethod is sending is of 528 bytes, but here after making ReadAsByteArrayAsync, the size becomes larger(706 bytes) and the values are also goofed up. Kind of banging my head against it, any help will be appreciated.

Thanks

推荐答案

得到了解决方案:

而不是

Got the solution:
instead of
mybytearray= response.Content.ReadAsByteArrayAsync().Result;



我在做:


I am doing:

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





关键点是:

它将字节数组作为base64encoded返回。



The key point is:
It was returning the byte array as base64encoded.


这篇关于如何从C#中的Web Api方法正确获取字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆