如何从C#中的Web Api方法正确获取字节数组?

时间:2014-05-27 08:09:14

标签: c# asp.net-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字节),并且值也会变得很快。 / p>

有点磕磕碰碰我的头,任何帮助都会受到赞赏。

谢谢!

7 个答案:

答案 0 :(得分:73)

实际上,HTTP可以处理" raw"二进制文件 - 协议本身是基于文本的,但有效负载可以是二进制文件(请参阅使用HTTP从Internet下载的所有文件)。

有一种方法可以在WebApi中执行此操作 - 您只需使用StreamContentByteArrayContent作为内容,因此它确实涉及一些手动工作:

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;
}

使用某些属性或其他东西可能会做同样的事情,但我不知道如何。

答案 1 :(得分:10)

HTTP是基于文本的协议编辑:HTTP也可以传输原始字节。 Luaan的答案更好。

返回的字节数组将以某种方式转换为文本,具体取决于服务器上MediaTypeFormatterCollection的设置方式以及HTTP客户端使用Accept标头请求的格式。字节通常由base64-encoding转换为文本。响应也可以进一步打包成JSON或XML,但预期长度(528)与实际长度(706)的比率似乎表示一个简单的base64字符串。

在客户端,您不会查看原始字节,而是查看此文本表示的字节。我会尝试将数据作为带有ReadAsStringAsync的字符串读取并检查它以查看它的格式。还要查看响应的标题。

然后,您应该相应地解析此文本以获取原始字节,例如与Convert.FromBase64String

答案 2 :(得分:8)

response.Content.ReadAsAsync<byte[]>().Result //Put this code in your client.

我想明确指出ReadAsAsync<byte[]>()ReadAsByteArrayAsync() NOT 的行为相同。

ReadAsByteArrayAsync()将所有转换为 Base64字节数组。它不会从response.Content获取非Base64 byte[],但ReadAsAsync<byte[]>()

答案 3 :(得分:3)

而不是这个

mybytearray = response.Content.ReadAsByteArrayAsync().Result;//Here is the problem

使用此

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

响应将字节数组返回为base64encoded。

答案 4 :(得分:1)

以此更改您的控制器,您将获得与发送的相同大小

[HttpPost]
[Route("SomeRoute")]
public FileStreamResult MyMethod([FromBody] string ID)
{
  byte[] mybytearray = db.getmybytearray(ID);
  return File(new MemoryStream(mybytearray), "application/octet-stream");
}

这是问题https://github.com/aspnet/Mvc/issues/7926

答案 5 :(得分:0)

从WEBAPI /服务器端,传递以下值:

String base64 = Convert.ToBase64String(bytes);     //Convert to ToBase64String

并从客户端接收值

response = client.GetAsync("URL/home/GetFIle?id=" + File_id).Result;

responseBody = await response.Content.ReadAsStringAsync();

mybytearray = Convert.FromBase64String(responseBody);    //Convert to FromBase64String

答案 6 :(得分:0)

这是我的工作方式

WEP API方法

            [HttpGet]
            [Route("pdfReport")]
            public byte[] ReportMRWiseCurrentStatus()
            {
    
                byte[] resultsarray = _materialRequestReportService.ReportMRWiseCurrentStatus();
                return resultsarray;
            }

客户

using (var client = new HttpClient())
            {
                var response = client.GetAsync(webApiUrl);
                if (response.Result.IsSuccessStatusCode)
                {

                    var result = response.Result.Content.ReadAsStringAsync().Result.Replace("\"", string.Empty);

                    var bytearray=Convert.FromBase64String(result);
                    System.IO.File.WriteAllBytes(@"C:\DB\newpdfAmila.pdf", bytearray);
                }

             }